poj3281

poj3281
根本想不到了网络流题,把牛拆点,如图方式建图,然后跑网络流

#include<iostream>
#include<cstdio>
#include<queue>
#include<algorithm>
#include<cmath>
#include<ctime>
#include<set>
#include<map>
#include<stack>
#include<cstring>
#define inf 2147483647
#define ls rt<<1
#define rs rt<<1|1
#define lson ls,nl,mid,l,r
#define rson rs,mid+1,nr,l,r
#define N 1000010
#define For(i,a,b) for(int i=a;i<=b;i++)
#define p(a) putchar(a)
#define g() getchar()

using namespace std;
int n,f,d,x,y,k,tot,maxflow,a[10010],b[10010];
int head[N],deep[N],cur[N];

struct node{
    int n;
    int v;
    int next;
}e[N];
queue<int>q;

void in(int &x){
    int y=1;
    char c=g();x=0;
    while(c<'0'||c>'9'){
        if(c=='-')y=-1;
        c=g();
    }
    while(c<='9'&&c>='0'){
        x=(x<<1)+(x<<3)+c-'0';c=g();
    }
    x*=y;
}
void o(int x){
    if(x<0){
        p('-');
        x=-x;
    }
    if(x>9)o(x/10);
    p(x%10+'0');
}

void push(int x,int y,int v){
    e[tot].n=y;
    e[tot].v=v;
    e[tot].next=head[x];
    head[x]=tot++;
}

bool bfs(int s,int t){
    memset(deep,-1,sizeof(deep));
    For(i,0,f+(n<<1)+d+2)
        cur[i]=head[i];
    deep[s]=0;
    q.push(s);
    while(!q.empty()){
        int now=q.front();
        q.pop();
        for(int i=head[now];i!=-1;i=e[i].next)
            if(deep[e[i].n]==-1&&e[i].v>0){
                deep[e[i].n]=deep[now]+1;
                q.push(e[i].n);
            }
    }
    return deep[t]!=-1;
}

int dfs(int now,int t,int lim){
    if(now==t||lim==0)
        return lim;
    int flow=0,F;
    for(int i=cur[now];i!=-1;i=e[i].next){
        cur[now]=i;
        if(deep[e[i].n]==deep[now]+1&&(F=dfs(e[i].n,t,min(lim,e[i].v)))){
            flow+=F;
            lim-=F;
            e[i].v-=F;
            e[i^1].v+=F;
            if(!lim)break;
        }
    }
    return flow;
}

void dinic(int s,int t){
    while(bfs(s,t))
        maxflow+=dfs(s,t,inf);        
}

int main(){
    in(n);in(f);in(d);
    memset(head,-1,sizeof(head));
    For(i,1,f){
        push(0,i,1);
        push(i,0,0);
    }
    For(i,1,n){
        push(i+f,i+n+f,1);
        push(i+n+f,i+f,0);
    }
    For(i,1,d){
        push(f+(n<<1)+i,f+(n<<1)+d+1,1);
        push(f+(n<<1)+d+1,f+(n<<1)+i,0);
    }
    For(i,1,n){
        in(x);in(y);
        For(j,1,x){
            in(k);
            push(k,f+i,1);
            push(f+i,k,0);
        }
        For(j,1,y){
            in(k);
            push(f+n+i,f+(n<<1)+k,1);
            push(f+(n<<1)+k,f+n+i,0);
        }
    }
    dinic(0,f+(n<<1)+d+1);
    o(maxflow);
    return 0;
}
原文地址:https://www.cnblogs.com/war1111/p/11207947.html