用的是kuangbin的模板:http://www.cnblogs.com/kuangbin/archive/2012/09/29/2707955.html
1 const int MAXN=20010;//点数的最大值 2 const int MAXM=880010;//边数的最大值 3 const int INF=0x3f3f3f3f; 4 5 struct Node 6 { 7 int from,to,next; 8 int cap; 9 }edge[MAXM]; 10 int tol; 11 int head[MAXN]; 12 int dep[MAXN]; 13 int gap[MAXN];//gap[x]=y :说明残留网络中dep[i]==x的个数为y 14 15 int n;//n是总的点的个数,包括源点和汇点 16 17 void init() 18 { 19 tol=0; 20 memset(head,-1,sizeof(head)); 21 } 22 23 void addedge(int u,int v,int w) 24 { 25 edge[tol].from=u; 26 edge[tol].to=v; 27 edge[tol].cap=w; 28 edge[tol].next=head[u]; 29 head[u]=tol++; 30 edge[tol].from=v; 31 edge[tol].to=u; 32 edge[tol].cap=0; 33 edge[tol].next=head[v]; 34 head[v]=tol++; 35 } 36 void BFS(int start,int end) 37 { 38 memset(dep,-1,sizeof(dep)); 39 memset(gap,0,sizeof(gap)); 40 gap[0]=1; 41 int que[MAXN]; 42 int front,rear; 43 front=rear=0; 44 dep[end]=0; 45 que[rear++]=end; 46 while(front!=rear) 47 { 48 int u=que[front++]; 49 if(front==MAXN)front=0; 50 for(int i=head[u];i!=-1;i=edge[i].next) 51 { 52 int v=edge[i].to; 53 if(dep[v]!=-1)continue; 54 que[rear++]=v; 55 if(rear==MAXN)rear=0; 56 dep[v]=dep[u]+1; 57 ++gap[dep[v]]; 58 } 59 } 60 } 61 int SAP(int start,int end) 62 { 63 int res=0; 64 BFS(start,end); 65 int cur[MAXN]; 66 int S[MAXN]; 67 int top=0; 68 memcpy(cur,head,sizeof(head)); 69 int u=start; 70 int i; 71 while(dep[start]<n) 72 { 73 if(u==end) 74 { 75 int temp=INF; 76 int inser; 77 for(i=0;i<top;i++) 78 if(temp>edge[S[i]].cap) 79 { 80 temp=edge[S[i]].cap; 81 inser=i; 82 } 83 for(i=0;i<top;i++) 84 { 85 edge[S[i]].cap-=temp; 86 edge[S[i]^1].cap+=temp; 87 } 88 res+=temp; 89 top=inser; 90 u=edge[S[top]].from; 91 } 92 if(u!=end&&gap[dep[u]-1]==0)//出现断层,无增广路 93 break; 94 for(i=cur[u];i!=-1;i=edge[i].next) 95 if(edge[i].cap!=0&&dep[u]==dep[edge[i].to]+1) 96 break; 97 if(i!=-1) 98 { 99 cur[u]=i; 100 S[top++]=i; 101 u=edge[i].to; 102 } 103 else 104 { 105 int min=n; 106 for(i=head[u];i!=-1;i=edge[i].next) 107 { 108 if(edge[i].cap==0)continue; 109 if(min>dep[edge[i].to]) 110 { 111 min=dep[edge[i].to]; 112 cur[u]=i; 113 } 114 } 115 --gap[dep[u]]; 116 dep[u]=min+1; 117 ++gap[dep[u]]; 118 if(u!=start)u=edge[S[--top]].from; 119 } 120 } 121 return res; 122 }