搭配飞行员
飞行大队有若干个来自各地的驾驶员,专门驾驶一种型号的飞机,这种飞机每架有两个驾驶员,需一个正驾驶员和一个副驾驶员。由于种种原因,例如相互配合的问题,有些驾驶员不能在同一架飞机上飞行,问如何搭配驾驶员才能使出航的飞机最多。
因为驾驶工作分工严格,两个正驾驶员或两个副驾驶员都不能同机飞行。
Input
第一行,两个整数
n
n
n 与
m
m
m,表示共有
n
n
n 个飞行员,其中有
m
m
m 名飞行员是正驾驶员。
下面有若干行,每行有
2
2
2 个数字
a
、
b
a、b
a、b。表示正驾驶员
a
a
a 和副驾驶员
b
b
b 可以同机飞行。
注:正驾驶员的编号在前,即正驾驶员的编号小于副驾驶员的编号。
Output
仅一行一个整数,表示最大起飞的飞机数。
Example
样例输入
10 5
1 7
2 6
2 10
3 7
4 8
5 9
样例输出
4
Hint
2 ≤ n ≤ 100 2≤n≤100 2≤n≤100
思路1
二分图匹配的模板题
#include <bits/stdc++.h>
using namespace std;
const int maxn=30000;
struct node{
int v,next;
}e[maxn];
int match[maxn],dismatch[maxn],vis[maxn],t,head[maxn],ans,m,n,u,v;
void add(int u,int v) {
t++;
e[t].v = v;
e[t].next = head[u];
head[u] = t;
}
bool dfs(int u) {
for (int i = head[u]; i; i = e[i].next) {
int v = e[i].v;
if (!vis[v]) {
vis[v] = 1;
if (!match[v] || dfs(match[v])) {
match[v] = u;
dismatch[u] = v;
return 1;
}
}
}
return 0;
}
int main() {
scanf("%d%d", &n, &m);
while (~scanf("%d%d", &u, &v)) {
add(u, v);
}
for (int i = 1; i <= n; i++) {
memset(vis, 0, sizeof(vis));
if (dfs(i)) {
ans++;
}
}
printf("%d\n", ans);
}
思路2
二分图最大匹配转化成网络流
把源点
S
S
S 与左边的点连一条容量为
1
1
1 的边
把右边的点与汇点
T
T
T 连一条容量为
1
1
1 的边
把左右能匹配的连一条容量为
1
1
1 的边
最后求最大流
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e6+7;
const int maxm=2e6+7;
const int inf=0x3f3f3f3f;
struct Dinic {
struct Edge {
int next, f, to;
} e[maxm];
int head[maxn], dep[maxn], tol, ans;
int cur[maxn];
int src, sink, n;
void add(int u, int v, int f) {
tol++;
e[tol].to = v;
e[tol].next = head[u];
e[tol].f = f;
head[u] = tol;
tol++;
e[tol].to = u;
e[tol].next = head[v];
e[tol].f = 0;
head[v] = tol;
}
bool bfs() {
queue<int> q;
memset(dep, -1, sizeof(dep));
q.push(src);
dep[src] = 0;
while (!q.empty()) {
int now = q.front();
q.pop();
for (int i = head[now]; i; i = e[i].next) {
if (dep[e[i].to] == -1 && e[i].f) {
dep[e[i].to] = dep[now] + 1;
if (e[i].to == sink)
return true;
q.push(e[i].to);
}
}
}
return false;
}
int dfs(int x, int maxx) {
if (x == sink)
return maxx;
for (int &i = cur[x]; i; i = e[i].next) {
if (dep[e[i].to] == dep[x] + 1 && e[i].f > 0) {
int flow = dfs(e[i].to, min(maxx, e[i].f));
if (flow) {
e[i].f -= flow;
e[i ^ 1].f += flow;
return flow;
}
}
}
return 0;
}
int dinic(int s, int t) {
ans = 0;
this->src = s;
this->sink = t;
while (bfs()) {
for (int i = 0; i <= n; i++)
cur[i] = head[i];
while (int d = dfs(src, inf))
ans += d;
}
return ans;
}
void init(int n) {
this->n = n;
memset(head, 0, sizeof(head));
tol = 1;
}
} G;
int n,m;
int main() {
//freopen("1.txt", "r", stdin);
scanf("%d%d", &n, &m);
int u, v;
int S = 0, T = n + 1;
G.init(T);
for (int i = 1; i <= m; i++) {
G.add(S, i, 1);
}
for (int i = m + 1; i <= n; i++) {
G.add(i, T, 1);
}
while (~scanf("%d%d", &u, &v)) {
G.add(u, v, 1);
}
printf("%d\n", G.dinic(S, T));
return 0;
}