# 【網絡流24題-洛谷-P2756】飛行員配對方案問題（二分圖最大匹配、最大流）

## 輸入輸出樣例

``````5 10
1 7
1 8
2 6
2 9
2 10
3 7
3 8
4 7
4 8
5 10
-1 -1``````

``````4
1 7
2 9
3 8
5 10 ``````

``````#include<stdio.h>
#include<string.h>
#include<queue>
#include<set>
#include<iostream>
#include<map>
#include<stack>
#include<cmath>
#include<algorithm>
#define ll long long
#define mod 1000000007
#define eps 1e-8
using namespace std;
const int MAXN = 10000;
const int MAXM = 100000;
const int INF = 0x3f3f3f3f;
struct Edge {
int to,next,cap,flow,cost;
} edge[MAXM];
int pre[MAXN],dis[MAXN];
bool vis[MAXN];
int N;//節點總個數，節點編號從 0 ～ N-1
void init(int n) {
N = n;
tol = 0;
}
void addedge(int u,int v,int cap,int cost) {
edge[tol].to = v;
edge[tol].cap = cap;
edge[tol].cost = cost;
edge[tol].flow = 0;
edge[tol].to = u;
edge[tol].cap = 0;
edge[tol].cost = -cost;
edge[tol].flow = 0;
}
bool spfa(int s,int t) {
queue<int>q;
for(int i = 0; i < N+1; i++) {
dis[i] = INF;
vis[i] = false;
pre[i] = -1;
}
dis[s] = 0;
vis[s] = true;
q.push(s);
while(!q.empty()) {
int u = q.front();
q.pop();
vis[u] = false;
for(int i = head[u]; i != -1; i = edge[i].next) {
int v = edge[i].to;
if(edge[i].cap > edge[i].flow && dis[v] > dis[u] + edge[i].cost ) {
dis[v] = dis[u] + edge[i].cost;
pre[v] = i;
if(!vis[v]) {
vis[v] = true;
q.push(v);
}
}
}
}
if(pre[t] == -1)return false;
else return true;
}
//返回的是最大流，cost 存的是最小費用
int minCostMaxflow(int s,int t,int &cost) {
int flow = 0;
cost = 0;
while(spfa(s,t)) {
int Min = INF;
for(int i = pre[t]; i != -1; i = pre[edge[i^1].to]) {
if(Min > edge[i].cap - edge[i].flow)
Min = edge[i].cap - edge[i].flow;
}
for(int i = pre[t]; i != -1; i = pre[edge[i^1].to]) {
edge[i].flow += Min;
edge[i^1].flow -= Min;
cost += edge[i].cost * Min;
}
flow += Min;
}
return flow;
}

int main()
{
int n,m;
scanf("%d%d",&m,&n);
init(n+m+2);
while(1){
int a,b;
scanf("%d%d",&a,&b);
if(a==-1&&b==-1)break;
}
for(int i=1;i<=m;i++)
{
}
for(int i=m+1;i<=m+n;i++)
{
}
int c;
int ans=minCostMaxflow(0,n+m+1,c);
if(ans==0){
puts("No Solution!");
}
else
{
printf("%d\n",ans);
for(int i=1;i<=m;i++)
{
if(edge[j].to!=0&&edge[j].to!=n+m+1&&edge[j].flow>0)
{
printf("%d %d\n",i,edge[j].to);
break;
}
}
}
}
return 0;
} ``````