UVA1658 Admiral 拆点法解决结点容量(路径不能有公共点,容量为1的时候) 最小费用最大流
/** 题目: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; }
posted on 2017-07-16 13:57 hnust_accqx 阅读(196) 评论(0) 编辑 收藏 举报