题意
有(n)个外籍飞行员和(m)个英国飞行员,每个外籍飞行员可以与若干英国飞行员配对。
每个飞行员最多只能使用一次,问最多可以有多少对飞行员,并输出方案。
思路
二分图裸题。
设置虚拟源点(S)和(T),从(S)向外籍飞行员节点连容量是(1)的边,从英国飞行员向(T)连容量是(1)的边(使用数量限制)
向外籍飞行员向可与之配对的英国飞行员连容量为正整数的边(使用数量之前已经限制了,因此只需要让其能流过去即可)
输出方案,遍历外籍飞行员与英国飞行员之间的反向边,若容量不为(0),则说明有流量,因此两点是配对的。
代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 110, M = 20210, inf = 1e8;
int n, m, S, T;
int h[N], e[M], ne[M], f[M], idx;
int cur[N], d[N];
void add(int a, int b, int c)
{
e[idx] = b, f[idx] = c, ne[idx] = h[a], h[a] = idx ++;
e[idx] = a, f[idx] = 0, ne[idx] = h[b], h[b] = idx ++;
}
bool bfs()
{
memset(d, -1, sizeof(d));
queue<int> que;
que.push(S);
d[S] = 0, cur[S] = h[S];
while(que.size()) {
int t = que.front();
que.pop();
for(int i = h[t]; ~i; i = ne[i]) {
int ver = e[i];
if(d[ver] == -1 && f[i]) {
d[ver] = d[t] + 1;
cur[ver] = h[ver];
if(ver == T) return true;
que.push(ver);
}
}
}
return false;
}
int find(int u, int limit)
{
if(u == T) return limit;
int flow = 0;
for(int i = cur[u]; ~i && flow < limit; i = ne[i]) {
cur[u] = i;
int ver = e[i];
if(d[ver] == d[u] + 1 && f[i]) {
int t = find(ver, min(f[i], limit - flow));
if(!t) d[ver] = -1;
f[i] -= t, f[i ^ 1] += t, flow += t;
}
}
return flow;
}
int dinic()
{
int res = 0, flow;
while(bfs()) {
while(flow = find(S, inf)) {
res += flow;
}
}
return res;
}
int main()
{
scanf("%d%d", &m, &n);
memset(h, -1, sizeof(h));
S = 0, T = n + 1;
for(int i = 1; i <= m; i ++) add(S, i, 1);
for(int i = m + 1; i <= n; i ++) add(i, T, 1);
while(true) {
int a, b;
scanf("%d%d", &a, &b);
if(a == -1) break;
add(a, b, inf);
}
printf("%d
", dinic());
for(int i = 0; i < idx; i += 2) {
if(e[i] > m && e[i] <= n && f[i ^ 1]) {
printf("%d %d
", e[i ^ 1], e[i]);
}
}
return 0;
}