题目:网络最大流
思路:模板题。注意存边的数组要开两倍。
代码:
#include<bits/stdc++.h>
using namespace std;#define maxn 10000
#define maxm 200000
#define inf (1<<30)
#define read(x) scanf("%d",&x);struct Edge {int u,v,w;Edge() {}Edge(int uu,int vv,int ww) {u=uu,v=vv,w=ww;}
};int n,m,s,t;
Edge e[maxm+5];
int g[maxm+5],nxt[maxm+5],cnt=-1;int d[maxm+5];
int cur[maxm+5];void add(int u,int v,int w) {e[++cnt]=Edge(u,v,w);nxt[cnt]=g[u];g[u]=cnt;
}void readin() {memset(g,-1,sizeof(g));memset(nxt,-1,sizeof(nxt));read(n);read(m);read(s);read(t);for(int i=1; i<=m; i++) {int u,v,w;read(u);read(v);read(w);add(u,v,w);add(v,u,0);}
}queue<int> que;bool bfs() {memset(d,0,sizeof(d));d[s]=1;que.push(s);while(!que.empty()) {int h=que.front();que.pop();for(int i=g[h]; ~i; i=nxt[i]) {Edge y=e[i];if(d[y.v]||y.w==0) continue;d[y.v]=d[h]+1;que.push(y.v);}}if(d[t]>0) return true;return false;
}int dfs(int x,int w) {if(x==t) return w;for(int& i=cur[x]; ~i; i=nxt[i]) {Edge y=e[i];if(d[y.v]!=d[x]+1||y.w==0) continue;int z=dfs(y.v,min(w,y.w));if(z) {e[i].w-=z;e[i^1].w+=z;return z;}}return 0;
}int slv() {int ans=0;while(bfs()) {for(int i=1; i<=n; i++) cur[i]=g[i];while(int x=dfs(s,inf)) ans+=x;}return ans;
}int main() {readin();int ans=slv();printf("%d",ans);return 0;
}