Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 62111 | Accepted: 23859 |
Description
Input
Output
Sample Input
5 4 1 2 40 1 4 20 2 4 20 2 3 30 3 4 10
Sample Output
50
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <queue> #define maxn 1000 + 100 #define maxm 2000 + 200 #define INF 0x3f3f3f3f using namespace std; int cnt, n, m; int dist[maxn]; int cur[maxn], vis[maxn]; int head[maxn]; struct node { int u, v, cap, flow, next; }; node edge[maxm]; void init(){ cnt = 0; memset(head, -1, sizeof(head)); } void add(int u,int v, int w){ edge[cnt] = {u, v, w, 0, head[u]}; //正建边 head[u] = cnt++; edge[cnt] = {v, u, 0, 0, head[v]}; //反建边 head[v] = cnt++; } void getmap(){ int u, v, w; while(m--){ scanf("%d%d%d", &u, &v, &w); add(u, v, w); } return ; } bool BFS(int st,int ed){ queue<int>q; memset(dist, -1, sizeof(dist)); memset(vis, 0, sizeof(vis)); q.push(st); dist[st] = 0; vis[st] = 1; while(!q.empty()){ int u = q.front(); q.pop(); for(int i = head[u]; i != -1; i = edge[i].next){ node E = edge[i]; if(!vis[E.v] && E.cap > E.flow){ vis[E.v] = 1; dist[E.v] = dist[u] + 1; if(E.v == ed) return true; q.push(E.v); } } } return false; } int DFS(int x, int ed, int a){ if(x == ed || a == 0) return a; int flow = 0, f; for(int &i = cur[x]; i != -1; i = edge[i].next){ node &E = edge[i]; if(dist[E.v] == dist[x] + 1 && (f = DFS(E.v, ed, min(a, E.cap - E.flow))) > 0){ E.flow += f; edge[i ^ 1].flow -= f; flow += f; a -= f; if(a == 0) break; } } return flow; } int maxflow(int st, int ed){ int flow = 0;; while(BFS(st, ed)){ memcpy(cur, head, sizeof(head)); flow += DFS(st, ed, INF); } return flow; } int main (){ while(scanf("%d%d", &m, &n) != EOF){ init(); getmap(); printf("%d\n",maxflow(1, n)); } return 0; }