UVa1658 Admiral (拆点法,最小费用流)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UVa1658 Admiral (拆点法,最小费用流)相关的知识,希望对你有一定的参考价值。
链接:http://vjudge.net/problem/UVA-1658
分析:把2到v-1的每个节点i拆成i和i‘两个结点,中间连一条容量为1,费用为0的边,然后求1到v的流量为2的最小费用流即可。
1 #include <cstdio> 2 #include<cstring> 3 #include<queue> 4 #include<vector> 5 #include<algorithm> 6 using namespace std; 7 8 const int maxn = 2000 + 5; 9 const int INF = 1000000000; 10 11 struct Edge { 12 int from, to, cap, flow, cost; 13 Edge(int u, int v, int c, int f, int w):from(u), to(v), cap(c), flow(f), cost(w) {} 14 }; 15 16 struct MCMF { 17 int n, m; 18 vector<Edge> edges; 19 vector<int> G[maxn]; 20 int inq[maxn]; 21 int d[maxn]; 22 int p[maxn]; 23 int a[maxn]; 24 25 void init(int n) { 26 this -> n = n; 27 for (int i = 0; i < n; i++) G[i].clear(); 28 edges.clear(); 29 } 30 31 void AddEdge(int from, int to, int cap, int cost) { 32 edges.push_back(Edge(from, to, cap, 0, cost)); 33 edges.push_back(Edge(to, from, 0, 0, -cost)); 34 m = edges.size(); 35 G[from].push_back(m - 2); 36 G[to].push_back(m - 1); 37 } 38 39 bool BellmanFord(int s, int t, int flow_limit, int& flow, int& cost) { 40 for (int i = 0; i < n; i++) d[i] = INF; 41 memset(inq, 0, sizeof(inq)); 42 d[s] = 0; inq[s] = 1; p[s] = 0; a[s] = INF; 43 44 queue<int> Q; 45 Q.push(s); 46 while (!Q.empty()) { 47 int u = Q.front(); Q.pop(); 48 inq[u] = 0; 49 for (int i = 0; i < G[u].size(); i++) { 50 Edge& e = edges[G[u][i]]; 51 if (e.cap > e.flow && d[e.to] > d[u] + e.cost) { 52 d[e.to] = d[u] + e.cost; 53 p[e.to] = G[u][i]; 54 a[e.to] = min(a[u], e.cap - e.flow); 55 if (!inq[e.to]) { Q.push(e.to); inq[e.to] = 1; } 56 } 57 } 58 } 59 if (d[t] == INF) return false; 60 if (flow + a[t] > flow_limit) a[t] = flow_limit - flow; 61 flow += a[t]; 62 cost += d[t] * a[t]; 63 for (int u = t; u != s; u = edges[p[u]].from) { 64 edges[p[u]].flow += a[t]; 65 edges[p[u] ^ 1].flow -= a[t]; 66 } 67 return true; 68 } 69 70 int MincostFlow(int s, int t, int flow_limit, int& cost) { 71 int flow = 0; cost = 0; 72 while (flow < flow_limit && BellmanFord(s, t, flow_limit, flow, cost)); 73 return flow; 74 } 75 }; 76 77 MCMF g; 78 79 int main() { 80 int v, e; 81 while (scanf("%d%d", &v, &e) == 2 && v) { 82 g.init(v * 2 - 2); 83 for (int i = 2; i <= v - 1; i++) 84 g.AddEdge(i - 1, v + i - 2, 1, 0); 85 int a, b, c; 86 while (e--) { 87 scanf("%d%d%d", &a, &b, &c); 88 if (a != 1 && a != v) a += v - 2; else a--; 89 b--; 90 g.AddEdge(a, b, 1, c); 91 } 92 int cost; 93 g.MincostFlow(0, v - 1, 2, cost); 94 printf("%d\n", cost); 95 } 96 return 0; 97 }
以上是关于UVa1658 Admiral (拆点法,最小费用流)的主要内容,如果未能解决你的问题,请参考以下文章