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

板子裸题
我永远热爱dinic

#include<bits/stdc++.h>
using namespace std;
#define IL inline
#define RG register
#define gi getint()
#define gc getchar()
#define File(a) freopen(a".in","r",stdin);freopen(a".out","w",stdout)
IL int getint()
{
    RG int xi=0;
    RG char ch=gc;
    bool f=0;
    while(ch<'0'|ch>'9')ch=='-'?f=1:f,ch=gc;
    while(ch>='0'&ch<='9')xi=(xi<<1)+(xi<<3)+ch-48,ch=gc;
    return f?-xi:xi;
}
IL void pi(int k,char ch=0)
{
    if(k<0)k=-k,putchar('-');
    if(k>=10)pi(k/10,0);
    putchar(k%10+'0');
    if(ch)putchar(ch);
}
IL unsigned int LOG2(unsigned int x)
{
    unsigned int ret;
    __asm__ __volatile__ ("bsrl %1, %%eax":"=a"(ret):"m"(x));
    return ret;
}
const int MAXN=100007;
int n,m,S,T;
struct E{
  int v,next,w;
}e[MAXN<<1];
int head[MAXN],cnt=-1;
int dep[MAXN];
int cur[MAXN];
IL void add(int u,int v,int w)
{
    e[++cnt]=(E){v,head[u],w};
    head[u]=cnt;
    e[++cnt]=(E){u,head[v],0};
    head[v]=cnt;
}
IL bool bfs()
{
    memset(dep,0,sizeof(dep));
    queue<int>Q;
    while(!Q.empty())Q.pop();
    Q.push(S);
    dep[S]=1;
    while(!Q.empty())
    {
        int now=Q.front();Q.pop();
        for(int i=head[now];~i;i=e[i].next)
            {
                int v=e[i].v;//printf("%d %d
",now,v);
                if(!dep[v]&&e[i].w)dep[v]=dep[now]+1,Q.push(v);            
            }
    }
    return dep[T];
}
IL int dfs(int p,int flow)
{
    if(p==T||!flow)return flow;
    int f,tmp=0;
    for(int &i=cur[p];~i;i=e[i].next)
        {
            int v=e[i].v;
            if(dep[v]==dep[p]+1&&e[i].w&&(f=dfs(v,min(flow,e[i].w))))
                {
                    tmp+=f;
                    flow-=f;
                    e[i].w-=f;
                    e[i^1].w+=f;
                    if(!flow)break;
                }
        }
    return tmp;
}
IL int dinic()
{
    int res=0;
    while(bfs())
    {
        memcpy(cur,head,(n<<2)+8);
        while(int dd=dfs(S,2147483647))res+=dd;
    }
    return res;
}
int main(void)
{
    fill(head,head+MAXN+1,-1);
    m=gi,n=gi;
    S=0,T=n+1;
    do{
        int u=gi,v=gi;
        add(u,v,1);
    }while(~e[cnt].v);
    for(int i=1;i<=m;i++)add(S,i,1);
    for(int i=m+1;i<=n;i++)add(i,T,1);
    int pp; 
    if(!(pp=dinic()))return printf("No Solution!")&0;
    else printf("%d
",pp);
    for(int i=0;i<=cnt;i+=2)if(e[i].v^S&&e[i^1].v^S&&e[i].v^T&&e[i^1].v^T&&e[i^1].w)printf("%d %d
",e[i^1].v,e[i].v);
    return 0;
}

原文地址:https://www.cnblogs.com/LLCSBlog/p/11195443.html