P2756 飞行员配对方案问题
这题很明显是可以用二分图做的,求二分图的最大匹配问题。然后就可以用二分图算法愉快地A掉此题,然后因为没有写二分图的做法我就不说了
对于条件一个飞行员只能在一架飞机上,那么从虚拟源点 -> 外籍飞行员连一个边权为
第二个就是配对的问题,我们对于能配对的,从外籍飞行员->英国飞行员建一条边权为
解读:源点和汇点是用来限制每个点的权值,从点权转移到边权,在这道题里点权是
第三个问题就是如何输出方案,本题要求的是外籍 对 英军,我们在跑完Dinic以后,如果匹配的话,说明他们之间的边流量为
代码如下
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn = 5020;
int n,m,str,end,tot = -1;
int head[maxn],deep[maxn],an[maxn];
LL ans;
struct node
{
int to,net,va;
}xuan[maxn<<1];
void add(int x,int y,int va)
{
xuan[++tot].net = head[x];
xuan[tot].to = y;
xuan[tot].va = va;
head[x] = tot;
}
bool bfs()
{
memset(deep,0,sizeof(deep));
deep[str] = 1;
queue<int> q;
q.push(str);
while(!q.empty())
{
int from = q.front();q.pop();
for(int i=head[from];i!=-1;i=xuan[i].net)
{
int to = xuan[i].to ;
int va = xuan[i].va ;
if(va&&(!deep[to]))
{
deep[to] = deep[from]+1;
q.push(to);
if(to==end)
return true;
}
}
}
return false;
}
LL dinic(int from,LL flow)
{
if(from==end)
return flow;
LL rest = flow;
for(int i=head[from];i!=-1;i=xuan[i].net)
{
int to = xuan[i].to ;
LL va = xuan[i].va ;
if(!rest)
return flow;
if(va&&deep[to]==deep[from]+1)
{
LL k = dinic(to,min(rest,va));
if(k==0)
deep[to] = 0;
if(k==1&&from<=m)
an[from] = to;
xuan[i].va -= k;
xuan[(i^1)].va += k;
rest -= k;
}
}
return flow - rest;
}
int main()
{
scanf("%d%d",&m,&n);
end = n+1;
memset(head,-1,sizeof(head));
for(int i=1;i<=m;i++)
{
add(str,i,1);
add(i,str,0);
}
for(int i=m+1;i<=n;i++)
{
add(i,end,1);
add(end,i,0);
}
while(1)
{
int a=0,b=0;
scanf("%d%d",&a,&b);
if(a==-1&&b==-1)
break;
add(a,b,1);
add(b,a,0);
}
while(bfs())
ans += dinic(str,2e9);
printf("%lld\n",ans);
for(int i=1;i<=m;i++)
{
for(int j=head[i];j!=-1;j=xuan[j].net)
{
int to = xuan[j].to ;
int va = xuan[j].va ;
if(m<to&&to<=n&&va==0)
printf("%d %d\n",i,to);
}
}
return 0;
}