Sap模板:邻接表
View Code
const int MM = 555555; #define maxint 0x3f3f3f3f int N,M,K; int S,T; struct Edge { int v,w,next; }edge[MM]; int head[MM],NE; void reset() {memset(head,-1,sizeof(head)),NE=0;} void add_edge(int u,int v,int c) { edge[NE].v=v, edge[NE].w=c, edge[NE].next=head[u]; head[u]=NE++; edge[NE].v=u, edge[NE].w=0, edge[NE].next=head[v]; head[v]=NE++; } int a[MM]; int gap[MM], dis[MM], pre[MM],cur[MM]; //返回s->t的最大流 int Sap(int s,int t) { memset(gap,0,sizeof(gap)); memset(dis,0,sizeof(dis)); int u,now,tmp,flow = 0; int v = t+1, i; a[u=s] = maxint, gap[0] = v; for(i=0; i<v ;i++) cur[i] = head[i]; while (dis[s]<v) { for(i=cur[u]; i!=-1;i=edge[i].next) if (edge[i].w && dis[u]==dis[edge[i].v] + 1) break; if(i!=-1) { tmp=edge[i].v; a[tmp]=min(a[u], edge[i].w); cur[u]=pre[tmp] = i; if ((u=tmp)==t) { flow += (tmp=a[t]); do { edge[pre[u]].w -= tmp; edge[pre[u]^1].w += tmp; u = edge[pre[u]^1].v; } while (u != s); a[s] = maxint; } } else { if ((-- gap[dis[u]])==0) break; dis[u] = v; cur[u] = head[u]; for (i = head[u]; i!=-1; i = edge[i].next) if (edge[i].w && dis[u] > dis[edge[i].v] + 1) dis[u] = dis[edge[i].v] + 1, cur[u] = i; gap[dis[u]] ++; if (u != s) u = edge[pre[u]^1].v; } } return flow; }
邻接矩阵:初始clear(edge,0)
int edge[333][333]; int gap[MM],dis[MM],pre[MM],cur[MM]; int flow[333][333];//存最大流的容量 int Sap(int s,int t,int nodenum) { memset(cur,0,sizeof(cur)); memset(dis,0,sizeof(dis)); memset(gap,0,sizeof(gap)); memset(flow,0,sizeof(flow)); int u=pre[s]=s,maxflow=0,aug=-1; gap[0]=nodenum; while(dis[s]<nodenum) { loop: for(int v=cur[u];v<nodenum;v++) if(edge[u][v]-flow[u][v] && dis[u]==dis[v]+1) { if(aug==-1 || aug>edge[u][v]-flow[u][v])aug=edge[u][v]-flow[u][v]; pre[v]=u; u=cur[u]=v; if(v==t) { maxflow+=aug; for(u=pre[u];v!=s;v=u,u=pre[u]) { flow[u][v]+=aug; flow[v][u]-=aug; } aug=-1; } goto loop; } int mindis=nodenum-1; for(int v=0;v<nodenum;v++) if(edge[u][v]-flow[u][v]&&mindis>dis[v]) { cur[u]=v; mindis=dis[v]; } if((--gap[dis[u]])==0)break; gap[dis[u]=mindis+1]++; u=pre[u]; } return maxflow; }