【题解】 P2756 飞行员配对方案问题⭐⭐【二分图匹配】
英国皇家空军从沦陷国征募了大量外籍飞行员。由皇家空军派出的每一架飞机都需要配备在航行技能和语言上能互相配合的2 名飞行员,其中1 名是英国飞行员,另1名是外籍飞行员。在众多的飞行员中,每一名外籍飞行员都可以与其他若干名英国飞行员很好地配合。如何选择配对飞行的飞行员才能使一次派出最多的飞机。对于给定的外籍飞行员与英国飞行员的配合情况,试设计一个算法找出最佳飞行员配对方案,使皇家空军一次能派出最多的飞机。
对于给定的外籍飞行员与英国飞行员的配合情况,编程找出一个最佳飞行员配对方案,使皇家空军一次能派出最多的飞机。
Input
第 1 行有 2 个正整数 m 和 n。n 是皇家空军的飞行员总数(n<100);m 是外籍飞行员数(m<=n)。外籍飞行员编号为 1~m;英国飞行员编号为 m+1~n。
接下来每行有 2 个正整数 i 和 j,表示外籍飞行员 i 可以和英国飞行员 j 配合。最后以 2个-1 结束。
Output
第 1 行是最佳飞行员配对方案一次能派出的最多的飞机数 M。接下来 M 行是最佳飞行员配对方案。每行有 2个正整数 i 和 j,表示在最佳飞行员配对方案中,飞行员 i 和飞行员 j 配对。如果所求的最佳飞行员配对方案不存在,则输出‘No Solution!’。
Examples
输入 #1 复制
5 10
1 7
1 8
2 6
2 9
2 10
3 7
3 8
4 7
4 8
5 10
-1 -1
输出 #1 复制
4
1 7
2 9
3 8
5 10
Hint
题意:
题解:
二分图匹配裸题, 学习一下匈牙利算法
经验小结:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <stdlib.h>
#include <vector>
#include <queue>
#include <cmath>
#include <stack>
#include <map>
#include <set>
using namespace std;
#define ms(x, n) memset(x,n,sizeof(x));
typedef long long LL;
const int inf = 1 << 30;
const LL maxn = 110;
const int maxm = 10010;
int N, M, match[maxn], head[maxm], ecnt;
bool used[maxn];
struct Edge{
int u, v, next;
}edges[maxm];
void addEdge(int u, int v){
edges[ecnt].u = u, edges[ecnt].v = v;
edges[ecnt].next = head[u], head[u] = ecnt++;
}
bool Dfs(int u){
used[u] = true;
for(int i = head[u]; i != -1; i = edges[i].next){
int v = edges[i].v, w = match[v];
if(w < 0 || !used[w] && Dfs(w)){
match[u] = v;
match[v] = u;
return true;
}
}
return false;
}
int Hungary(){
int res = 0;
ms(match, -1);
for(int i = M+1; i <= N; ++i)
if(match[i] < 0){
ms(used, 0);
if(Dfs(i))
++res;
}
return res;
}
void init(){
ms(head, -1);
ecnt = 0;
}
int main()
{
init();
int u, v;
cin >> M >> N;
while(cin >> u >> v && u!=-1 && v!=-1){
addEdge(u, v);
addEdge(v, u);
}
int ans = Hungary();
if(ans == 0)
cout << "No Solution\n";
else{
cout << ans << endl;
for(int i = 1; i <= M; ++i)
if(match[i] > 0)
cout << i << ' ' << match[i] << endl;
}
return 0;
}