「网络流24题」飞行员配对方案问题-题解

题目传送门: 「Luogu P2756」飞行员配对方案数问题

题目大意

输入两方飞行员个数$m,n$,再给定两方飞行员可以配合的人编号$i,j$(以$-1,-1$结束)
输出最多配对数和配对方案

题解

主要在建图
皇家空军与源点$s$连容量$1$的边,外籍与汇点$t$连容量$1$的边,可配合的两点间连容量为$1$的边
输出最大流即可(要找配对方案)

也可以使用匈牙利算法(本文不给出)

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <bits/stdc++.h>
using namespace std;

const int maxn = 120;
const int inf = 0x3f3f3f3f;

int n, m, s, t;
int d[maxn], cur[maxn];

struct Edge {
int from, to, cap, flow;
Edge(int u, int v, int c, int f): from(u), to(v), cap(c), flow(f){};
};
vector<Edge> edges;
vector<int> G[maxn];

void add(int u, int v, int c) {
edges.push_back(Edge(u, v, c, 0));
edges.push_back(Edge(v, u, 0, 0));
int mm = edges.size();
G[u].push_back(mm - 2);
G[v].push_back(mm - 1);
}

bool vis[maxn];
bool bfs() {
memset(vis, 0, sizeof(vis));
queue<int> Q;
Q.push(s);
d[s] = 0;
vis[s] = 1;
while (!Q.empty()) {
int x = Q.front(); Q.pop();
for (int i = 0; i < G[x].size(); ++i) {
Edge& e = edges[G[x][i]];
if (!vis[e.to] && e.cap > e.flow) {
vis[e.to] = 1;
d[e.to] = d[x] + 1;
Q.push(e.to);
}
}
}
return vis[t];
}

int dfs(int x, int a) {
if (x == t || a == 0) return a;
int flow = 0, f;
for (int& i = cur[x]; i < G[x].size(); ++i) {
Edge& e = edges[G[x][i]];
if (d[x] + 1 == d[e.to] && (f = dfs(e.to, min(a, e.cap - e.flow))) > 0) {
e.flow += f;
edges[G[x][i] ^ 1].flow -= f;
flow += f;
a -= f;
if (a == 0) break;
}
}
return flow;
}

int MaxFlow(int s, int t) {
int flow = 0;
while (bfs()) {
memset(cur, 0, sizeof(cur));
flow += dfs(s, inf);
}
return flow;
}

int main() {
scanf("%d %d", &m, &n);
s = 0; t = n + 1;
int u, v;
while (scanf("%d %d", &u, &v) == 2 && u != -1 && v != -1) {
add(u, v, 1);
}
for (int i = 1; i <= m; ++i) {
add(s, i, 1);
}
for (int i = m + 1; i <= n; ++i) {
add(i, t, 1);
}
int flow = MaxFlow(s, t);
if (flow == 0) {
printf("No Solution!\n");
return 0;
}
printf("%d\n", flow);
for (int i = 0; i < edges.size(); i = i + 2) {
if (edges[i].from != s && edges[i].to != t) {
if (edges[i].flow != 0) {
printf("%d %d\n", edges[i].from, edges[i].to);
}
}
}
return 0;
}

「网络流24题」飞行员配对方案问题-题解

https://blog.tonycrane.cc/p/154ff24f.html

作者

TonyCrane

发布于

2019-04-30

更新于

2020-05-05

许可协议