1. 程式人生 > >UVA1349 Optimal Bus Route Design 拆點法+最小費用最佳匹配

UVA1349 Optimal Bus Route Design 拆點法+最小費用最佳匹配

新建 can cnblogs main route edge 要求 name int

/**
題目:UVA1349 Optimal Bus Route Design
鏈接:https://vjudge.net/problem/UVA-1349
題意:lrj入門經典P375
給n個點(n<=100)的有向帶權圖,找若幹個有向圈,每個點恰好屬於一個圈。要求權和盡量小。註意即使(u,v)
和(v,y)都存在,他們的權值也不一定相同。
思路:拆點法+最小費用最佳完美匹配。
如果每個點都有一個唯一的後繼(不同的點沒有相同的後繼點,且只有一個後繼),那麽每個點一定恰好屬於一個圈。
聯想到二分圖匹配。
(u,v) 表示 u->v有向邊。
左邊一側全是u,右邊一側全是v。
u與若幹個v有指向關系u->v。

每一個點都扮演著u,v的指向位置關系。指向別的點,被別的點指向,都是唯一性。

對每一個點拆分成兩個點,前者指向別的點(作為u),後者被別的點指向(作為v)。

新建源點s,指向所有的u。 新建匯點t,被所有的v指向。容量為1,花費為0.

假設點X,拆分成Xu,Xv。
如果(X,Y)。 那麽讓Xu指向Yv.(s->Xu->Yv->t)

然後求解最小費用最佳完美匹配。

拆分點的方法:對於點k,可以拆分成2*k,2*k+1.
如果從s出發的流都是滿載,那麽存在最佳完美匹配。
*/ #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 = 210; 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]; } return true; } int MincostMaxflow(int s,int t,long long &cost){ int flow = 0; cost = 0; while(BellmanFord(s,t,flow,cost)); return flow; } }; int n; int main() { while(scanf("%d",&n)==1&&n){ int s, t; s = 1, t = 2*n+2; MCMF mcmf; mcmf.init(t); ///s -> front for(int i = 1; i <= n; i++) mcmf.AddEdge(s,2*i,1,0); ///back -> t for(int i = 1; i <= n; i++) mcmf.AddEdge(2*i+1,t,1,0); ///front -> back for(int i = 1; i <= n; i++){ int u = i, v, w; while(scanf("%d",&v)==1&&v){ scanf("%d",&w); mcmf.AddEdge(2*u,2*v+1,1,w); } } long long cost; int flow = mcmf.MincostMaxflow(s,t,cost); if(flow==n){ printf("%lld\n",cost); }else printf("N\n"); } return 0; }

UVA1349 Optimal Bus Route Design 拆點法+最小費用最佳匹配