【网络流24题】1.飞行员配对方案问题

二分图匹配问题,因为隶属于网络流24题,就用网络流写一下。
从源点向每个外籍飞行员连一条容量为1的流,每个外籍飞行员向可以配合的英国飞行员连一条容量为1的流,每个英国飞行员向汇点连一条容量为1的流,跑一边最大流即可。
(网络流24题大多需要spj,所以需要一个有spj的oj,本系列代码均在www.oj.swust.edu.cn测试通过)

#include<cstdio>
#include<cstdlib>
#include<ctime>
#include<cmath>
#include<cstring>
#include<string>
#include<iomanip>
#include<iostream>
#include<algorithm>
using namespace std;
#define INF 100000000
struct my_flow
{
    int l,r,f;
    bool pd;
}a[1000000];
int fir[1000000];
int nex[1000000];
int tot=1;
void add_edge(int l,int r,int f,bool pd=false)
{
    a[++tot].l=l;
    a[tot].r=r;
    a[tot].f=f;
    a[tot].pd=pd;
    nex[tot]=fir[l];
    fir[l]=tot;

}
int d[1000000];
int s=0,t=999999;
bool bfs()
{
    static int dui[1000000];
    int top=1;
    int my_final=2;
    memset(d,-1,sizeof(d));
    dui[top]=s;
    d[s]=1;
    while(top<my_final)
    {
        int u=dui[top++];
        for(int o=fir[u];o;o=nex[o])
        {
            if(a[o].f && d[a[o].r]==-1)
            {
                d[a[o].r]=d[u]+1;
                if(a[o].r==t) return true;
                dui[my_final++]=a[o].r;
            }
        }

    }
    return false;
}
int dinic(int u,int flow)
{
    if(u==t) return flow;
    int left=flow;
    for(int o=fir[u];o;o=nex[o])
    {
        if(a[o].f && left && d[a[o].r]==d[u]+1)
        {
            int temp=dinic(a[o].r,min(left,a[o].f));
            if(!temp) d[a[o].r]=-1;
            left-=temp;
            a[o].f-=temp;
            a[o^1].f+=temp;
        }
    }
    return flow-left;
}
int main()
{
    int m,n;
    scanf("%d%d",&m,&n);
    for(int i=1;i<=m;i++)
    {
        add_edge(s,i,1);
        add_edge(i,s,0);
    }
    for(int i=1;i<=n;i++)
    {
        add_edge(m+i,t,1);
        add_edge(t,m+i,0);
    }
    while(1)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        if(x==-1 &&y==-1) break;
        add_edge(x,m+y,1,1);
        add_edge(m+y,x,0);
    }
    int ans=0;
    while(bfs()) ans+=dinic(s,INF);
    cout<<ans<<endl;
    for(int i=1;i<=m;i++)
        for(int o=fir[i];o;o=nex[o])
            if(!a[o].f && a[o].pd) printf("%d %d\n",a[o].l,a[o].r-m);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值