#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #define MAXN 21050 #define MAXINT 2100000000 using namespace std; struct edge { int f,c,v; edge *next,*rev; edge(){}; edge(int ver,int cap,edge *nex):v(ver),c(cap),f(0),next(nex),rev(NULL){}; void* operator new(size_t,void *p) { return p; } }*s[MAXN]; int dis[MAXN],num[MAXN]; int n,m; int src,des; int u[10001],v[10001],w[10001]; int un; int a[10001],b[10001]; int nu; void init() { int queue[MAXN],head=0,tail=0; for (int i=0;i<=des;i++) dis[i]=MAXN,num[i]=0; queue[tail++]=des; dis[des]=0; num[0]=1; while (head!=tail) { int v=queue[head++]; for (edge *e=s[v];e;e=e->next) { if ((e->rev&&e->rev->c==0)||dis[e->v]<MAXN) continue; dis[e->v]=dis[v]+1; ++num[dis[e->v]]; queue[tail++]=e->v; } } } int maxflow() { int st=src,ret=0; edge *E[MAXN],*rep[MAXN]; for (int i=0;i<=n+1;i++) E[i]=s[i]; while (dis[src]<des) { if (st==des) { int delta=MAXINT; for (int i=src;i!=des;i=E[i]->v) delta=min(delta,E[i]->c); for (int i=src;i!=des;i=E[i]->v) { E[i]->c-=delta; E[i]->rev->c+=delta; E[i]->f+=delta; E[i]->rev->f-=delta; } ret+=delta; st=src; } edge *e; for (e=E[st];e;e=e->next) if (e->c>0&&dis[st]==dis[e->v]+1) break; if (e) { E[st]=e; rep[e->v]=e->rev; st=e->v; } else { if ((--num[dis[st]])==0) break; E[st]=s[st]; int mind=n; for (edge *t=s[st];t;t=t->next) if (t->c>0) mind=min(mind,dis[t->v]); dis[st]=mind+1; ++num[dis[st]]; if (st!=src) st=rep[st]->v; } } return ret; } int main() { freopen("flyer.in","r",stdin); freopen("flyer.out","w",stdout); scanf("%d%d",&n,&m); src=0,des=n+1; while (~scanf("%d%d",&u[un],&v[un]))w[un++]=1; u[un]=0;v[un]=0; for (int i=1;i<=m;i++) u[un]=0,v[un]=i,w[un++]=1; for (int i=m+1;i<=n;i++) u[un]=i,v[un]=n+1,w[un++]=1; edge *buffer=new edge[un*2]; edge *data=buffer; for (int i=0;i<un;i++) { s[u[i]]=new((void*) data++)edge(v[i],w[i],s[u[i]]); s[v[i]]=new((void*) data++)edge(u[i],0,s[v[i]]); s[u[i]]->rev=s[v[i]]; s[v[i]]->rev=s[u[i]]; } init(); printf("%d",maxflow()); }
原文地址:http://blog.csdn.net/creationaugust/article/details/43671183