1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| bool spfa(int s,int t) { memset(dis,0x3f,sizeof(dis)); memset(vis,0,sizeof(vis)); dis[s]=0; queue<int> q; q.push(s); while(!q.empty()) { int u=q.front(); q.pop(); for(int i=head[u];i;i=ne[i]) { int v=to[i]; if(cap[i] && dis[v]>dis[u]+cost[i]) { dis[v]=dis[u]+cost[i]; if(!vis[v]) q.push(v); } } } return dis[t]!=inf; }
int dfs(int u,int f) { if(u==t || f==0) return f; vis[u]=1; int flow=0,d; for(int i=head[u];i;i=ne[i]) { int v=to[i]; if(!vis[v] && dis[v]==dis[u]+cost[i] && (d=dfs(v,min(f,cap[i])))) { flow+=d,f-=d,cap[i]-=d,cap[i^1]+=d,res+=d*cost[i]; if(f==0) break; } } vis[u]=0; return flow; }
ll mcmf(int s,int t) { ll flow=0; while(spfa(s,t)) flow+=dfs(s,inf); return flow; }
|