P2756,ssl2601-飞行员配对问题【网络流24题,最大匹配,dinic】

正题

链接:
https://www.luogu.org/record/show?rid=7921243


大意

就是有n个飞行员,m个外籍的,然后皇家的和外籍的配对求最大匹配


解题思路

裸网络流二分匹配。
建图:
源点S连向左边的点,右边点连汇点E,然后之间连接,所以的边容量都是1


代码

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct line{
    int to,next,w;
}a[100010];
int n,m,x,y,d[110],tot,state[110];
int head,tail,ls[110],s,e,ans;
void addl(int x,int y,int w)
{
    a[tot].to=y;a[tot].next=ls[x];
    a[tot].w=w;ls[x]=tot++;
    a[tot].to=x;a[tot].next=ls[y];
    a[tot].w=0;ls[y]=tot++;
}
bool bfs()//在残量网上建立分层图
{
    head=0;tail=1;
    memset(d,-1,sizeof(d));
    d[s]=0;state[1]=s;
    do
    {
        head++;
        int x=state[head];
        for (int q=ls[x];q;q=a[q].next)
        {
            int y=a[q].to;
            if (a[q].w>0 && d[y]==-1)
            {
                d[y]=d[x]+1;
                state[++tail]=y;
                if (y==e) return true;//可以到达
            }
        }
    }
    while (head<tail);
    return false;//不可以到达汇点了
} 
int dinic(int x,int flow)
{
    int rest=0,k;
    if (x==e) return flow;
    for (int q=ls[x];q;q=a[q].next)
    {
        int y=a[q].to;
        if (a[q].w>0 && d[y]==d[x]+1)
        {
            rest+=(k=dinic(y,min(a[q].w,flow-rest)));
            //记录流量
            a[q].w-=k;//减去剩余容量
            a[q^1].w+=k;//反向加上流量
        }
    }
    if (!rest) d[x]=0;//剪枝
    return rest;
}
int main()
{
    scanf("%d%d",&n,&m);
    s=m+1;e=m+2;
    while (1)
    {
        scanf("%d%d",&x,&y);
        if (x==-1 && y==-1) break;
        addl(x,y,1);//连接
    }
    for (int i=1;i<=n;i++) addl(s,i,1);
    for (int i=n+1;i<=m;i++) addl(i,e,1);
    while (bfs()) 
      ans+=dinic(s,1e9);
    if (ans==0)
    {
        printf("No Solution!");
        return 0;
    }
    printf("%d\n",ans);
    for (int i=0;i<tot;i+=2)
    {
        if (a[i].to!=s&&a[i^1].to!=s&&a[i].to!=e&&a[i^1].to!=e)
        //判断是在中间用于匹配的边
          if (a[i^1].w!=0)//有流过的
            printf("%d %d\n",a[i^1].to,a[i].to);//输出
    }
}

转载于:https://www.cnblogs.com/sslwyc/p/9218509.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值