Luo Gu P3386 bipartite graph matching problem solution

Face questions

While this question is to practice Hungarian algorithm, but can be used to cut it off the network flow;

We can build a super source and sink a super, super source connection point of the left part, the right part of the super-exchange connection points;

The maximum flow is then run on the drawing it;

PS: My source is a super set of 2001, super exchange is 2002;

 

#include <bits/stdc++.h>
using namespace std;
struct littlestar{
    int to;
    int nxt;
    int w;
}star[5000010];
int head[5000010],cnt;
inline void add(int u,int v,int w)
{
    star[++cnt].to=v;
    star[cnt].nxt=head[u];
    star[cnt].w=w;
    head[u]=cnt;
    
}
int n,m,e;
int dis[3010];
queue<int> q;
inline bool bfs()
{
    memset(dis,0,sizeof(dis));
    while(q.size()){
        q.pop();
    }
    q.push(2001);
    dis[2001]=1;
    while(q.size()){
        int u=q.front();
        q.pop();
        for(int i=head[u];i;i=star[i].nxt){
            int v=star[i].to;
            if(star[i].w&&!dis[v]){
                q.push(v);
                dis[v]=dis[u]+1;
                if(v==2002){
                    return 1;
                }
            }
        }
    }
    return 0;
}
int dinic(int u,int flow)
{
    if(u==2002){
        return flow;
    }
    int rest=flow;
    int tmp;
    for(register int i=head[u];i&&rest;i=star[i].nxt){
        int v=star[i].to;
        if(star[i].w&&dis[v]==dis[u]+1){
            tmp=dinic(v,min(rest,star[i].w));
            if(!tmp) dis[v]=0;
            star[i].w-=tmp;
            star[i^1].w+=tmp;
            rest-=tmp;
        }
    }
    return flow-rest;
}
int maxflow;
int main()
{
    scanf("%d%d%d",&n,&m,&e);
    for(register int i=1;i<=n;i++){
        add(2001,i,1);
        add(i,2001,0);
    }
    for(register int i=1;i<=m;i++){
        add(n+i,2002,1);
        add(2002,n+i,0);
    }
    for(register int i=1;i<=e;i++){
        int u,v;
        scanf("%d%d",&u,&v);
        add(u,n+v,1);
        add(n+v,u,0);
    }
    int flow=0;
    while(bfs()){
        while(flow=dinic(2001,999999999)) maxflow+=flow;
    }
    cout<<maxflow;
}

 

Guess you like

Origin www.cnblogs.com/kamimxr/p/11331586.html