题目
求有向无环图的最大流。
分析
dinic
代码
#include <bits/stdc++.h>
using namespace std;
struct node{int y,next,w;}e[200001];
int k=1,ls[10001],n,dis[10001],s,t,m,x,y,w,ans;
int in(){
int ans=0; char c=getchar();
while (!isdigit(c)) c=getchar();
while (isdigit(c)) ans=ans*10+c-48,c=getchar();
return ans;
}
void add(int x,int y,int w){
e[++k].y=y; e[k].w=w; e[k].next=ls[x]; ls[x]=k;
e[++k].y=x; e[k].w=0; e[k].next=ls[y]; ls[y]=k;
}
bool bfs(int s){//分层图
for (int i=1;i<=n;i++) dis[i]=0;
queue<int>q; q.push(s); dis[s]=1;
while (q.size()){
int x=q.front(); q.pop();
for (int i=ls[x];i;i=e[i].next)
if (e[i].w>0&&!dis[e[i].y]){
dis[e[i].y]=dis[x]+1;
if (e[i].y==t) return 1;
q.push(e[i].y);
}
}
return 0;
}
int min(int a,int b){return (a<b)?a:b;}
int dfs(int x,int now){//寻找增广路dinic
if (x==t) return now;
int rest=now;
for (int i=ls[x];i;i=e[i].next)
if (e[i].w>0&&dis[e[i].y]==dis[x]+1){
int f=dfs(e[i].y,min(e[i].w,rest));
if (!f) dis[e[i].y]=0;
e[i].w-=f; e[i^1].w+=f; rest-=f;
}
return now-rest;
}
int main(){
n=in(); m=in(); s=in(); t=in();
for (int i=1;i<=m;i++){
x=in(); y=in(); w=in();
add(x,y,w);
}
while (bfs(s)) ans+=dfs(s,1e7);
return !printf("%d",ans);
}