您的位置:首页 > 其它

UVa1658 Admiral(拆点法+最小费用流)

2016-03-30 17:32 399 查看
题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=51253

【思路】

固定流量的最小费用流。

拆点,将u拆分成u1和u2,连边(u1,u2,1,0)表示只能经过该点一次。跑流量为2的最小费用流。

【代码】

1 #include<cstdio>
2 #include<cstring>
3 #include<queue>
4 #include<vector>
5 #define FOR(a,b,c) for(int a=(b);a<(c);a++)
6 using namespace std;
7
8 const int maxn = 4000+10;
9 const int INF = 1e9;
10
11 struct Edge{ int u,v,cap,flow,cost;
12 };
13
14 struct MCMF {
15     int n,m,s,t;
16     int inq[maxn],a[maxn],d[maxn],p[maxn];
17     vector<int> G[maxn];
18     vector<Edge> es;
19
20     void init(int n) {
21         this->n=n;
22         es.clear();
23         for(int i=0;i<n;i++) G[i].clear();
24     }
25     void AddEdge(int u,int v,int cap,int cost) {
26         es.push_back((Edge){u,v,cap,0,cost});
27         es.push_back((Edge){v,u,0,0,-cost});
28         m=es.size();
29         G[u].push_back(m-2);
30         G[v].push_back(m-1);
31     }
32
33     bool SPFA(int s,int t,int flowlimit,int& flow,int& cost) {
34         for(int i=0;i<n;i++) d[i]=INF;
35         memset(inq,0,sizeof(inq));
36         d[s]=0; inq[s]=1; p[s]=0; a[s]=INF;
37         queue<int> q; q.push(s);
38         while(!q.empty()) {
39             int u=q.front(); q.pop(); inq[u]=0;
40             for(int i=0;i<G[u].size();i++) {
41                 Edge& e=es[G[u][i]];
42                 int v=e.v;
43                 if(e.cap>e.flow && d[v]>d[u]+e.cost) {
44                     d[v]=d[u]+e.cost;
45                     p[v]=G[u][i];
46                     a[v]=min(a[u],e.cap-e.flow);        //min(a[u],..)
47                     if(!inq[v]) { inq[v]=1; q.push(v);
48                     }
49                 }
50             }
51         }
52         if(d[t]==INF) return false;
53         if(flow+a[t] > flowlimit) a[t] = flowlimit-flow;
54         flow+=a[t] , cost+=a[t]*d[t];
55         for(int x=t; x!=s; x=es[p[x]].u) {
56             es[p[x]].flow+=a[t]; es[p[x]^1].flow-=a[t];
57         }
58         return true;
59     }
60     int Mincost(int s,int t,int flowlimit,int& cost) {
61         int flow=0; cost=0;
62         while(flow<flowlimit && SPFA(s,t,flowlimit,flow,cost)) ;
63         return flow;
64     }
65 } mc;
66
67 int n,m;
68
69 int main() {
70     while(scanf("%d%d",&n,&m)==2) {
71         mc.init(n+n);
72         int u,v,w;
73         FOR(i,0,m) {
74             scanf("%d%d%d",&u,&v,&w);
75             u--,v--;
76             mc.AddEdge(n+u,v,1,w);
77         }
78         FOR(i,0,n) mc.AddEdge(i,n+i,1,0);
79         int cost,flow;
80         flow=mc.Mincost(n+0,n-1,2,cost);
81         printf("%d\n",cost);
82     }
83     return 0;
84 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: