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
| #include <queue> using namespace std; const int N = + 10, M = + 10, inf = 1e9; int n, st, ed, d[N], cur[N]; int idx, hd[N], nxt[M], edg[M], wt[M]; bool bfs () { for (int i = st; i <= ed; ++i) d[i] = -1; d[st] = 0; cur[st] = hd[st]; queue <int> q; q.push(st); while (!q.empty()) { int t = q.front(); q.pop(); for (int i = hd[t]; ~i; i = nxt[i]) if (!~d[edg[i]] && wt[i]) { cur[edg[i]] = hd[edg[i]]; d[edg[i]] = d[t] + 1; if (edg[i] == ed) return true; q.push(edg[i]); } } return false; } int dfs (int x, int k) { if (x == ed) return k; int res = 0; for (int i = cur[x]; ~i && res < k; i = nxt[i]) { cur[x] = i; if (d[edg[i]] == d[x] + 1 && wt[i]) { int t = dfs(edg[i], min(wt[i], k - res)); if (!t) d[edg[i]] = -1; res += t; wt[i] -= t, wt[i ^ 1] += t; } } return res; } int dinic () { int res = 0, flow; while (bfs()) while (flow = dfs(st, inf)) res += flow; return res; } void add (int a, int b, int c) { nxt[idx] = hd[a], hd[a] = idx, edg[idx] = b, wt[idx++] = c; }
|