码迷,mamicode.com
首页 > Web开发 > 详细

UVa820 Internet Bandwidth (最大流)

时间:2016-09-25 20:23:44      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

链接:http://bak3.vjudge.net/problem/UVA-820

分析:最大流模板题。

 

 1 #include <cstdio>
 2 #include <queue>
 3 #include <cstring>
 4 #include <vector>
 5 using namespace std;
 6 
 7 const int maxn = 100 + 5;
 8 const int INF = 0x3f3f3f3f;
 9 
10 struct Edge {
11     int from, to, cap, flow;
12     Edge(int u, int v, int c, int f):from(u), to(v), cap(c), flow(f) {}
13 };
14 
15 struct EdmondsKarp {
16     int n, m;
17     vector<Edge> edges;
18     vector<int> G[maxn];
19     int a[maxn];
20     int p[maxn];
21 
22     void init(int n) {
23         for (int i = 0; i < n; i++) G[i].clear();
24         edges.clear();
25     }
26 
27     void AddEdge(int from, int to, int cap) {
28         edges.push_back(Edge(from, to, cap, 0));
29         edges.push_back(Edge(to, from, 0, 0));
30         m = edges.size();
31         G[from].push_back(m - 2);
32         G[to].push_back(m - 1);
33     }
34 
35     int Maxflow(int s, int t) {
36         int flow = 0;
37         for (;;) {
38             memset(a, 0, sizeof(a));
39             queue<int> Q;
40             Q.push(s);
41             a[s] = INF;
42             while (!Q.empty()) {
43                 int x = Q.front(); Q.pop();
44                 for (int i = 0; i < G[x].size(); i++) {
45                     Edge& e = edges[G[x][i]];
46                     if (!a[e.to] && e.cap > e.flow) {
47                         p[e.to] = G[x][i];
48                         a[e.to] = min(a[x], e.cap - e.flow);
49                         Q.push(e.to);
50                     }
51                 }
52                 if (a[t]) break;
53             }
54             if (!a[t]) break;
55             for (int u = t; u != s; u = edges[p[u]].from) {
56                 edges[p[u]].flow += a[t];
57                 edges[p[u] ^ 1].flow -= a[t];
58             }
59             flow += a[t];
60         }
61         return flow;
62     }
63 };
64 
65 EdmondsKarp g;
66 int cap[maxn][maxn];
67 
68 int main() {
69     int n, s, t, m, kase = 0;
70     while (scanf("%d", &n) == 1 && n) {
71         g.init(n + 1);
72         scanf("%d%d%d", &s, &t, &m);
73         memset(cap, 0, sizeof(cap));
74         for (int i = 0, u, v, w; i < m; i++) {
75             scanf("%d%d%d", &u, &v, &w);
76             cap[u][v] += w;
77             cap[v][u] = cap[u][v];
78         }
79         for (int i = 1; i <= n; i++)
80             for (int j = i + 1; j <= n; j++)
81                 if (cap[i][j]) {
82                     g.AddEdge(i, j, cap[i][j]);
83                     g.AddEdge(j, i, cap[i][j]);
84                 }
85         printf("Network %d\nThe bandwidth is %d.\n\n", ++kase, g.Maxflow(s, t));
86     }
87     return 0;
88 }

 

UVa820 Internet Bandwidth (最大流)

标签:

原文地址:http://www.cnblogs.com/XieWeida/p/5906619.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!