洛谷P3376 【模板】网络最大流
1 #include<bits/stdc++.h> 2 #define LL long long 3 #define GG int 4 #define For(i, j, k) for(int i=j; i<=k; i++) 5 #define Dow(i, j, k) for(int i=j; i>=k; i--) 6 using namespace std; 7 inline GG read() { 8 GG x = 0, f = 1; 9 char ch = getchar(); 10 while(ch<'0'||ch>'9') { if(ch=='-') f = -1; ch = getchar(); } 11 while(ch>='0'&&ch<='9') { x = x*10+ch-48; ch = getchar(); } 12 return x * f; 13 } 14 inline void write(GG x) { 15 if(x<0) putchar('-'), x = -x; 16 if(x>9) write(x/10); 17 putchar(x%10+48); 18 } 19 inline void writeln(GG x) { 20 write(x); puts(""); 21 } 22 23 const int N = 10011, M = 100011, INF = 1e9; 24 int n, m, S, T, nedge; 25 struct edge{ 26 int to, pre, v; 27 }e[M*2]; 28 int head[N], dep[N], cur[N]; 29 30 inline void add(int x, int y, int v) { 31 e[++nedge].to = y; 32 e[nedge].pre = head[x]; 33 e[nedge].v = v; 34 head[x] = nedge; 35 } 36 37 inline void init() { 38 n = read(); m = read(); S = read(); T = read(); 39 nedge = -1; 40 memset(head, -1, sizeof(head)); 41 For(i, 1, m) { 42 int x = read(), y = read(), v = read(); 43 add(x, y, v); add(y, x, 0); 44 } 45 } 46 47 int dfs(int u, int dist) { 48 if(u == T) return dist; 49 for(int& i=cur[u]; i!=-1; i=e[i].pre) { 50 int v = e[i].to; 51 if(e[i].v>0 && dep[v]==dep[u]+1) { // > 52 int flow = dfs(v, min(e[i].v, dist)); 53 if(flow>0) { 54 e[i].v -= flow; 55 e[i^1].v += flow; 56 return flow; 57 } 58 } 59 } 60 return 0; 61 } 62 63 inline int bfs() { 64 For(i, 0, n) dep[i] = 0; 65 queue<int> Q; 66 Q.push(S); dep[S] = 1; 67 68 while(!Q.empty()) { 69 int u = Q.front(); Q.pop(); 70 for(int i=head[u]; i!=-1; i=e[i].pre) { 71 int v = e[i].to; 72 if(e[i].v>0 && dep[v]==0) { 73 dep[v] = dep[u]+1; 74 Q.push(v); 75 } 76 } 77 } 78 if(dep[T]==0) 79 return 0; 80 else 81 return 1; 82 } 83 84 inline void Dinic() { 85 int ans = 0; 86 while(bfs()) { 87 For(i, 1, n) cur[i] = head[i]; 88 while(int d=dfs(S, INF)) 89 ans += d; 90 } 91 writeln(ans); 92 } 93 94 int main() { 95 init(); 96 Dinic(); 97 }