完全的模板,做多了就好了吧
反向流量真的很有意思,有这样一种说法比较容易理解。”正向是+,反向就是-,其实是等价的。因为每次找到的增广路不一定是最优解里面的,所以再进行后面的操作的时候要重新选择,而反向流量就类似于回溯的作用。相当于撤销了刚才选择的u->v的流“。
1 #include <iostream> 2 #include <cstdio> 3 #include <queue> 4 #include <algorithm> 5 #define INF 999999999 6 //#define OPEN_FILE 7 using namespace std; 8 9 const int MAXN = 201, MAXM = 201, MAXL = 100001; 10 struct Node 11 { 12 int id, v; 13 }; 14 int cap[MAXM][MAXM], flow[MAXM][MAXM], a[MAXM], f[MAXM]; 15 int ans, n, m; 16 void ek_bfs() 17 { 18 int u, v, s, t; 19 s = 1; 20 t = m; 21 ans = 0; 22 queue<int> d; 23 while (1){ 24 memset(a, 0, sizeof(a)); 25 a[s] = INF; 26 d.push(s); 27 while (!d.empty()){ 28 u = d.front(); 29 d.pop(); 30 for (v = s; v <= t; v++){ 31 if (a[v] || cap[u][v] <= flow[u][v]) continue; 32 f[v] = u; 33 d.push(v); 34 a[v] = min(a[u], cap[u][v] - flow[u][v]); 35 } 36 } 37 if (a[t] == 0) break; 38 for (u = t; u != s; u = f[u]){ 39 flow[f[u]][u] += a[t]; 40 flow[u][f[u]] -= a[t]; 41 } 42 ans += a[t]; 43 } 44 } 45 int main() 46 { 47 #ifdef OPEN_FILE 48 freopen("in.txt", "r", stdin); 49 freopen("out.txt", "w", stdout); 50 #endif // OPEN_FILE 51 int i, x, y, z; 52 while (~scanf("%d%d", &n, &m)){ 53 memset(flow, 0, sizeof(flow)); 54 memset(cap, 0, sizeof(cap)); 55 for (i = 1; i <= n; i++){ 56 scanf("%d%d%d", &x, &y, &z); 57 cap[x][y] += z; 58 } 59 ek_bfs(); 60 printf("%d ", ans); 61 } 62 }