求一次最大流后,分别对所有满流的边的容量+1,然后看是否存在增广路。
1 #include<cstdio> 2 #include<cstring> 3 #include<queue> 4 #include<algorithm> 5 using namespace std; 6 #define INF (1<<30) 7 #define MAXN 555 8 #define MAXM 11111 9 10 struct Edge{ 11 int v,cap,flow,next; 12 }edge[MAXM]; 13 int vs,vt,NE,NV; 14 int head[MAXN]; 15 16 void addEdge(int u,int v,int cap){ 17 edge[NE].v=v; edge[NE].cap=cap; edge[NE].flow=0; 18 edge[NE].next=head[u]; head[u]=NE++; 19 edge[NE].v=u; edge[NE].cap=0; edge[NE].flow=0; 20 edge[NE].next=head[v]; head[v]=NE++; 21 } 22 23 int level[MAXN]; 24 int gap[MAXN]; 25 void bfs(){ 26 memset(level,-1,sizeof(level)); 27 memset(gap,0,sizeof(gap)); 28 level[vt]=0; 29 gap[level[vt]]++; 30 queue<int> que; 31 que.push(vt); 32 while(!que.empty()){ 33 int u=que.front(); que.pop(); 34 for(int i=head[u]; i!=-1; i=edge[i].next){ 35 int v=edge[i].v; 36 if(level[v]!=-1) continue; 37 level[v]=level[u]+1; 38 gap[level[v]]++; 39 que.push(v); 40 } 41 } 42 } 43 44 int pre[MAXN]; 45 int cur[MAXN]; 46 int ISAP(bool statue){ 47 bfs(); 48 memset(pre,-1,sizeof(pre)); 49 memcpy(cur,head,sizeof(head)); 50 int u=pre[vs]=vs,flow=0,aug=INF; 51 gap[0]=NV; 52 while(level[vs]<NV){ 53 bool flag=false; 54 for(int &i=cur[u]; i!=-1; i=edge[i].next){ 55 int v=edge[i].v; 56 if(edge[i].cap!=edge[i].flow && level[u]==level[v]+1){ 57 flag=true; 58 pre[v]=u; 59 u=v; 60 //aug=(aug==-1?edge[i].cap:min(aug,edge[i].cap)); 61 aug=min(aug,edge[i].cap-edge[i].flow); 62 if(v==vt){ 63 if(statue&&aug) return 1; 64 flow+=aug; 65 for(u=pre[v]; v!=vs; v=u,u=pre[u]){ 66 edge[cur[u]].flow+=aug; 67 edge[cur[u]^1].flow-=aug; 68 } 69 //aug=-1; 70 aug=INF; 71 } 72 break; 73 } 74 } 75 if(flag) continue; 76 int minlevel=NV; 77 for(int i=head[u]; i!=-1; i=edge[i].next){ 78 int v=edge[i].v; 79 if(edge[i].cap!=edge[i].flow && level[v]<minlevel){ 80 minlevel=level[v]; 81 cur[u]=i; 82 } 83 } 84 if(--gap[level[u]]==0) break; 85 level[u]=minlevel+1; 86 gap[level[u]]++; 87 u=pre[u]; 88 } 89 return flow; 90 } 91 int main(){ 92 int n,m,a,b,c; 93 scanf("%d%d",&n,&m); 94 vs=0; vt=n-1; NV=n; NE=0; 95 memset(head,-1,sizeof(head)); 96 while(m--){ 97 scanf("%d%d%d",&a,&b,&c); 98 addEdge(a,b,c); 99 } 100 ISAP(0); 101 int cnt=0; 102 for(int i=0; i<NE; i+=2){ 103 if(edge[i].flow!=edge[i].cap) continue; 104 ++edge[i].cap; 105 if(ISAP(1)) ++cnt; 106 --edge[i].cap; 107 } 108 printf("%d",cnt); 109 return 0; 110 }