1. 程式人生 > >UVA1658 Admiral 拆點法解決結點容量(路徑不能有公共點,容量為1的時候) 最小費用最大流

UVA1658 Admiral 拆點法解決結點容量(路徑不能有公共點,容量為1的時候) 最小費用最大流

ear ace == void for include () size max

/**
題目:UVA1658 Admiral
鏈接:https://vjudge.net/problem/UVA-1658
題意:lrj入門經典P375
求從s到t的兩條不相交(除了s和t外,沒有公共點)的路徑,使得權值和最小。

思路:拆點法。
除了s,t外。把其他點都拆成兩個。

例如點A,拆成A和A‘。A指向A‘連一條容量為1,花費為0的邊。
原來指向A的,仍然指向A點。
原來A指向其他點的,由A‘指向它們。

最小費用最大流求流量為2時候的最小費用即可。

*/
#include<iostream>
#include<cstring>
#include<vector>
#include
<map> #include<cstdio> #include<algorithm> #include<queue> using namespace std; const int INF = 0x3f3f3f3f; typedef long long LL; const int N = 2100; struct Edge{ int from, to, cap, flow, cost; Edge(int u,int v,int c,int f,int w):from(u),to(v),cap(c),flow(f),cost(w){} };
struct MCMF{ int n, m; vector<Edge> edges; vector<int> G[N]; int inq[N]; int d[N]; int p[N]; int a[N]; void init(int n){ this->n = n; for(int i = 0; i <= n; i++) G[i].clear(); edges.clear(); } void AddEdge(int from,int
to,int cap,long long cost){ edges.push_back(Edge(from,to,cap,0,cost)); edges.push_back(Edge(to,from,0,0,-cost)); m = edges.size(); G[from].push_back(m-2); G[to].push_back(m-1); } bool BellmanFord(int s,int t,int &flow,long long &cost){ for(int i = 0; i <= n; i++) d[i] = INF; memset(inq, 0, sizeof inq); d[s] = 0; inq[s] = 1; p[s] = 0; a[s] = INF; queue<int> Q; Q.push(s); while(!Q.empty()){ int u = Q.front(); Q.pop(); inq[u] = 0; for(int i = 0; i < G[u].size(); i++){ Edge& e = edges[G[u][i]]; if(e.cap>e.flow&&d[e.to]>d[u]+e.cost){ d[e.to] = d[u]+e.cost; p[e.to] = G[u][i]; a[e.to] = min(a[u],e.cap-e.flow); if(!inq[e.to]) {Q.push(e.to); inq[e.to] = 1;} } } } if(d[t]==INF) return false; flow += a[t]; cost += (long long)d[t]*(long long)a[t]; for(int u = t; u!=s; u = edges[p[u]].from){ edges[p[u]].flow+=a[t]; edges[p[u]^1].flow-=a[t]; } ///流量為2時的最小費用。 if(flow==2){ return false; } return true; } int MincostMaxflow(int s,int t,long long &cost){ int flow = 0; cost = 0; while(BellmanFord(s,t,flow,cost)); return flow; } }; vector<int>node[N]; int main() { int n, m; while(scanf("%d%d",&n,&m)==2) { int s = 1, t = n; int u, v; long long cost; MCMF mcmf; mcmf.init(n*2); for(int i = 1; i <= n; i++) node[i].clear(); for(int i = 0; i < m; i++){ scanf("%d%d%lld",&u,&v,&cost); node[u].push_back(v); node[u].push_back(cost); } int tot = n+1; for(int i = 0; i < node[1].size(); i+=2){ mcmf.AddEdge(1,node[1][i],1,node[1][i+1]); } for(int i = 2; i < n; i++){///除了源點和匯點,其他拆點 int from = i, to = tot++; mcmf.AddEdge(from,to,1,0); for(int j = 0; j < node[i].size(); j+=2){ mcmf.AddEdge(to,node[i][j],1,node[i][j+1]); } } for(int i = 0; i < node[n].size(); i+=2){ mcmf.AddEdge(n,node[n][i],1,node[n][i+1]); } mcmf.MincostMaxflow(s,t,cost); printf("%lld\n",cost); } return 0; }

UVA1658 Admiral 拆點法解決結點容量(路徑不能有公共點,容量為1的時候) 最小費用最大流