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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| #include<bits/stdc++.h> using namespace std; #define int long long inline int read(){int x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1; ch=getchar();}while(ch>='0'&&ch<='9'){x=(x<<1)+ (x<<3)+(ch^48);ch=getchar();}return x*f;} #define Z(x) (x)*(x) #define pb push_back
#define N 500010 struct node { int x, y, z, n; }d[N]; int n, m, i, j, k; int h[N], H[N], dep[N]; int u, v, w, S, T, ans; queue<int>q; void cun(int x, int y, int z) {
d[++k].x=x; d[k].y=y; d[k].z=z; d[k].n=h[x]; h[x]=k; } int bfs() { while(!q.empty()) q.pop(); memset(dep, -1, sizeof(dep)); memcpy(h, H, sizeof(H)); dep[S]=1; q.push(S); while(!q.empty()) { u=q.front(); q.pop();
for(int g=h[u]; g; g=d[g].n) { v=d[g].y; w=d[g].z;
if(w<=0 || dep[v]!=-1) continue; dep[v]=dep[u]+1; q.push(v); } }
return dep[T]!=-1; } int dfs(int x, int w) { if(x==T) return w; if(!w) return 0; int ans=0, s; for(int &i=h[x]; i; i=d[i].n) { int y=d[i].y, z=d[i].z; if(dep[y]!=dep[x]+1) continue; if(z<=0) continue; s=dfs(y, min(w, z)); ans+=s; w-=s; d[i].z-=s; d[i^1].z+=s; if(!w) break; } return ans; } signed main() {
n=read(); m=read(); S=read(); T=read(); for(i=1, k=1; i<=m; ++i) { u=read(); v=read(); w=read(); cun(u, v, w); cun(v, u, 0); } memcpy(H, h, sizeof(h)); while(bfs()) ans+=dfs(S, 1e18); printf("%lld", ans); return 0; }
|