一共有n 个飞行员,其中有 m 个外籍飞行员和 (n−m)
个英国飞行员,外籍飞行员从 1 到 m 编号,英国飞行员从 m+1 到 n 编号。
对于给定的外籍飞行员与英国飞行员的配合情况,设计一个算法找出最佳飞行员配对方案,使皇家空军一次能派出最多的飞机。
二分图板子题
用网络流输出时,判断w[i]==0 && w[i^1]>0
#include <iostream>
#include<cmath>
#include <queue>
#include <cstring>
using namespace std;
const int N =2e6+2,M=5e4+100;
int g[N],a[N],L;
const int inf =1e9+7;
int all=1,hd[N],go[M],w[M],nxt[M];
int S,T,n,m;
int dis[M],ans=0,now[M];
void add_(int x,int y,int z){
nxt[++all]=hd[x]; hd[x]=all; go[all]=y;
w[all]=z;
swap(x,y);
nxt[++all]=hd[x]; hd[x]=all; go[all]=y;
w[all]=0;
}
bool bfs(){
for(int i=0;i<M;i++)dis[i]=inf;
queue<int> q;
q.push(S);
now[S]=hd[S];
dis[S]=0;
while(q.empty()==0){
int x=q.front();
q.pop();
for(int i=hd[x];i;i=nxt[i]){
int y=go[i];
if(w[i]>0&&dis[y]==inf){
dis[y]=dis[x]+1;
now[y]=hd[y];
q.push(y);
if(y==T) return 1;
}
}
}
return 0;
}
int dfs(int x,int sum){
if(x==T) return sum;
int k,res=0;
for(int i=now[x];i&& sum ;i=nxt[i]){
now[x]=i;
int y=go[i];
if(w[i]>0&&(dis[y]==dis[x]+1)){
k=dfs(y,min(sum,w[i]));
if(k==0) dis[y]=inf;
w[i]-=k;
w[i^1]+=k;
res+=k;
sum-=k;
}
}
return res;
}
signed main(){
int i,x,y;
cin>>m>>n;
S=0,T=n+1;
for(i=1;i<=m;i++) add_(S,i,1);
while(cin>>x>>y,~x&&~y){
add_(x,y,1);
}
for(i=m+1;i<=n;i++) add_(i,T,1);
int ans =0;
while(bfs()) ans+=dfs(S,inf) ;
cout<<ans<<endl;
for(i=1;i<=m;i++)
for(int k=hd[i];k;k=nxt[k]){
int y=go[k];
if(y!=S&&w[k]==0&&w[k^1]){
cout<<i<<' '<<y<<endl;
}
}
}
浙公网安备 33010602011771号