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 80 81 82 83 84 85 86 87 88 89
| #include <queue> #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int MAXN = 430; const int MAX_INT = (1 << 30);
struct Edge{ int v, nxt, w; };
struct Node{ int v, id; };
int n, m, ecnt; bool vis[MAXN]; int head[MAXN]; Node pre[MAXN]; Edge edge[MAXN];
void init(){ ecnt = 0; memset(edge, 0, sizeof(edge)); memset(head, -1, sizeof(head)); }
void addEdge(int u, int v, int w){ edge[ecnt].v = v; edge[ecnt].w = w; edge[ecnt].nxt = head[u]; head[u] = ecnt++; }
bool bfs(int s, int t){ queue <int> que; memset(vis, 0, sizeof(vis)); memset(pre, -1, sizeof(pre)); pre[s].v = s; vis[s] = true; que.push(s); while(!que.empty()){ int u = que.front(); que.pop(); for(int i = head[u]; i + 1; i = edge[i].nxt){ int v = edge[i].v; if(!vis[v] && edge[i].w){ pre[v].v = u; pre[v].id = i; vis[v] = true; if(v == t) return true; que.push(v); } } } return false; }
int EK(int s, int t){ int ans = 0; while(bfs(s, t)){ int mi = MAX_INT; for(int i = t; i != s; i = pre[i].v){ mi = min(mi, edge[pre[i].id].w); } for(int i = t; i != s; i = pre[i].v){ edge[pre[i].id].w -= mi; edge[pre[i].id ^ 1].w += mi; } ans += mi; } return ans; }
int main(){ while(scanf("%d%d", &m, &n) != EOF){ init(); int u, v, w; for(int i = 0; i < m; i++){ scanf("%d%d%d", &u, &v, &w); addEdge(u, v, w); addEdge(v, u, 0); } printf("%d\n", EK(1, n)); } return 0; }
|