HDU 1853 MCMF
生活随笔
收集整理的這篇文章主要介紹了
HDU 1853 MCMF
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題意:給定一個有向帶權圖,使得每一個點都在一個環上,而且權之和最小。
分析:每個點在一個環上,入度 = 出度 = 1,拆點入點,出點,s到所有入點全部滿載的最小費用MCMF;
#include <bits/stdc++.h>using namespace std;const int maxn = 105*2; const int INF = 0x3f3f3f3f;typedef pair<int,int> pii;struct Edge {int from, to, cap, flow, cost; };struct MCMF {int n, m;vector<Edge> edges;vector<int> G[maxn];bool inq[maxn]; // 是否在隊列中int d[maxn]; // Bellman-Fordint p[maxn]; // 上一條弧int a[maxn]; // 可改進量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, int 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){memset(inq,0,sizeof(inq));for(int i=0;i<n;i++)d[i] = INF;d[s] = 0;inq[s] = true;p[s] = 0;a[s] = INF;queue<int> Q;Q.push(s);while(!Q.empty()){int u = Q.front();Q.pop();inq[u] = false;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] = true;}}}}if(d[t] == INF) return false; //s-t 不連通,失敗退出flow += a[t];cost += (long long)d[t] * (long long)a[t];int u = t;while(u != s){edges[p[u]].flow += a[t];edges[p[u]^1].flow -= a[t];u = edges[p[u]].from;}return true;}pair<long long,int>Mincost(int s, int t){long long cost = 0;int flow = 0;while(BellmanFord(s, t, flow, cost));return pair<int,long long>{flow,cost};} }sol;int main() {int n,m;while(scanf("%d%d",&n,&m)!=EOF) {int s = 0,t=2*n+1;sol.init(2*n+2);for(int i=1;i<=n;i++)sol.AddEdge(s,i,1,0);for(int i=n+1;i<=2*n;i++)sol.AddEdge(i,t,1,0);for(int i=0;i<m;i++) {int u,v,c;scanf("%d%d%d",&u,&v,&c);sol.AddEdge(u,v+n,1,c);}pii ans = sol.Mincost(s,t);if(ans.first!=n)puts("-1");else cout<<ans.second<<endl;}return 0; }?
轉載于:https://www.cnblogs.com/TreeDream/p/7283629.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的HDU 1853 MCMF的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: js 标准对象
- 下一篇: c3p0数据库连接池+mysql数据库基