题目背景
第二次世界大战时期..
题目描述
英国皇家空军从沦陷国征募了大量外籍飞行员。由皇家空军派出的每一架飞机都需要配备在航行技能和语言上能互相配合的2 名飞行员,其中1 名是英国飞行员,另1名是外籍飞行员。在众多的飞行员中,每一名外籍飞行员都可以与其他若干名英国飞行员很好地配合。如何选择配对飞行的飞行员才能使一次派出最多的飞机。对于给定的外籍飞行员与英国飞行员的配合情况,试设计一个算法找出最佳飞行员配对方案,使皇家空军一次能派出最多的飞机。
对于给定的外籍飞行员与英国飞行员的配合情况,编程找出一个最佳飞行员配对方案,使皇家空军一次能派出最多的飞机。
输入输出格式
输入格式:
第 1 行有 2 个正整数 m 和 n。n 是皇家空军的飞行员总数(n<100);m 是外籍飞行员数(m<=n)。外籍飞行员编号为 1~m;英国飞行员编号为 m+1~n。
接下来每行有 2 个正整数 i 和 j,表示外籍飞行员 i 可以和英国飞行员 j 配合。最后以 2个-1 结束。
输出格式:
第 1 行是最佳飞行员配对方案一次能派出的最多的飞机数 M。接下来 M 行是最佳飞行员配对方案。每行有 2个正整数 i 和 j,表示在最佳飞行员配对方案中,飞行员 i 和飞行员 j 配对。如果所求的最佳飞行员配对方案不存在,则输出‘No Solution!’。
输入输出样例
输入样例#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
解题思路
先建图,自己假设一个源点s,一个汇点t。从s到1~m的容量为1,从m+1~n到t的容量也为1,输入的配对i, j,从i到j的容量也为1,反向弧都初始化为0。然后用dinic算法求最大流,最大流量就是最大匹配数,从i到j的弧变成饱和弧了的,就输出i,j。
代码如下
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
#include <cmath>
#define s 0
#define t 210
#define INF 0x3f3f3f3f
using namespace std;
struct Line{
int l, r, w;
Line() = default;
Line(int l, int r, int w): l(l), r(r), w(w){ }
};
vector<Line> line;
vector<int> g[255];
int deep[255];
bool bfs()
{
queue<int> que;
memset(deep, 0, sizeof(deep));
que.push(s);
deep[s] = 1;
while(!que.empty()){
int top = que.front();
que.pop();
for(int i = 0; i < g[top].size(); i ++){
int z = g[top][i];
if(!deep[line[z].r] && line[z].w){
deep[line[z].r] = deep[top] + 1;
que.push(line[z].r);
if(deep[t])
return true;
}
}
}
return false;
}
int dfs(int x, int mix)
{
if(x == t || !mix)
return mix;
int ap = 0;
for(int i = 0; i < g[x].size(); i ++){
int z = g[x][i];
if(deep[x] < deep[line[z].r] && line[z].w){
int p = dfs(line[z].r, min(mix, line[z].w));
mix -= p;
ap += p;
line[z].w -= p;
line[z^1].w += p;
if(!mix)
return ap;
}
}
return ap;
}
int dinic()
{
int ans = 0;
while(bfs()){
ans += dfs(s, INF);
}
return ans;
}
int main()
{
int m, n;
while(cin >> m >> n){
for(int i = 1; i <= m; i ++){
line.push_back(Line(s, i, 1));
g[s].push_back(line.size() - 1);
line.push_back(Line(s, i, 0));
g[i].push_back(line.size() - 1);
}
for(int i = m + 1; i <= m + n; i ++){
line.push_back(Line(i, t, 1));
g[i].push_back(line.size() - 1);
line.push_back(Line(t, i, 0));
g[t].push_back(line.size() - 1);
}
int x, y;
while(cin >> x >> y && x != -1 && y != -1){
line.push_back(Line(x, y, 1));
g[x].push_back(line.size() - 1);
line.push_back(Line(y, x, 0));
g[y].push_back(line.size() - 1);
}
int ans = dinic();
if(ans){
cout << ans << endl;
for(int i = 2 * (m + n); i < line.size(); i += 2){
if(!line[i].w)
cout << line[i].l << " " << line[i].r << endl;
}
}
else
cout << "No Solution!" << endl;
for(int i = s; i <= t; i ++)
g[i].clear();
line.clear();
}
}

探讨二次世界大战期间,英国皇家空军如何通过算法优化外籍与英国飞行员的配对,以实现最大化的飞机派遣效率。该算法基于图论与最大流理论,通过构建特定的图结构并应用dinic算法,确定最佳的飞行员配对方案。
398





