杭电1532----Drainage Ditches『最大流』

 1 /*
 2 网络流的最大流问题
 3 刚学习Dinic算法。模版题
 4  */
 5 #include <cstring>
 6 #include <cstdio>
 7 #include <queue>
 8 using namespace std;
 9 const int maxn = 205;
10 const int inf = 0x3f3f3f3f;
11 struct
12 {
13     int c,f;
14 }edge[maxn][maxn];
15 int dis[maxn];
16 int v,e;
17 bool bfs()
18 {
19     memset(dis,0,sizeof dis);
20     queue<int> q;
21     q.push(1);
22     dis[1] = 1;
23     while(!q.empty())
24     {
25         int u = q.front(); q.pop();
26         for(int i = 1; i <= v; ++i)
27             if(!dis[i] && edge[u][i].c > edge[u][i].f)
28             {dis[i] = dis[u] + 1;q.push(i);}
29     }
30     return dis[v] != 0;
31 }
32 int dfs(int u,int c)
33 {
34     if(u == v) return c;
35     int temp = c;
36     for(int i = 1; i <= v && temp; ++i)
37     {
38         if(dis[i] != dis[u] + 1 || edge[u][i].c <= edge[u][i].f) continue;
39         int t = dfs(i,min(temp,edge[u][i].c - edge[u][i].f));
40         edge[u][i].f += t; edge[i][u].f -= t; temp -= t;
41     }
42     return c - temp;
43 }
44 int dinic()
45 {
46     int ans = 0;
47     while(bfs())
48         while(int t = dfs(1,inf))
49             ans += t;
50     return ans;
51 }
52 int main()
53 {
54     while(~scanf("%d%d",&e,&v))
55     {
56         memset(edge,0,sizeof edge);
57         while(e--)
58         {
59             int x,y,z;
60             scanf("%d%d%d",&x,&y,&z);
61             edge[x][y].c += z;
62         }
63         int ans = dinic();
64         printf("%d\n",ans);
65     }
66     return 0;
67 }

 

posted @ 2017-08-15 21:20  Posase  阅读(190)  评论(0编辑  收藏  举报