zoj 3362 Beer Problem 最小費用流

來源:互聯網
上載者:User

       別人都說是赤裸裸的最小費用流,自己想了很久,都想不到如何做,最後看了別人解題報告才懂。

       關鍵還是在構圖和轉化。源點是1,添加一個匯點,匯點到各個城市的邊的容量是各個城市賣啤酒的錢的相反數。通過spfa求cost的最短路徑,若最短路徑的cost小於0,說明這條路徑是賺錢的,否則是虧本的,演算法停止。

#include<iostream>#include <queue>#include <cstdio>#include <cstring>using namespace std;const int N = 105;const int M = 2005;const int INF = 1000000000;struct edge{int v;int cap;int cost;int next;};edge E[M*4+N*2];int head[N];int cost[N];int pre_v[N], pre_e[N];bool inQ[N];int n, m;int cnt;void add_edge(int u, int v, int cap, int cost){E[cnt].v = v;E[cnt].cap = cap;E[cnt].cost = cost;E[cnt].next = head[u];head[u] = cnt++;E[cnt].v = u;E[cnt].cap = 0;E[cnt].cost = -cost;E[cnt].next = head[v];head[v] = cnt++;}int mcmf(int s, int t, int n){queue<int> Q;int u;int mincost = 0;while (1){memset(inQ, false, sizeof(inQ));//memset(pre_e, -1, sizeof(pre_e));memset(pre_v, -1, sizeof(pre_v));Q.push(s);for (int i = 0; i < n; i++)cost[i] = INF;cost[s] = 0;inQ[s] = true;//spfa//根據每條邊的cost求最短路while (!Q.empty()){u = Q.front();Q.pop();inQ[u] = false;for (int i = head[u]; i != -1; i = E[i].next){int v = E[i].v;if (E[i].cap && cost[u] + E[i].cost < cost[v]){cost[v] = cost[u] + E[i].cost;if (!inQ[v]){Q.push(v);inQ[v] = true;}pre_v[v] = u; pre_e[v] = i;}}}//當cost[t]大於0時,說明當前的買賣時虧本的,退出if (cost[t] >= 0)break;int f = INF;for (int i = t; i != s; i = pre_v[i]){int v = pre_e[i];f = min(f, E[v].cap);}mincost += f*cost[t];for (int i = t; i != s; i = pre_v[i]){int u = pre_e[i];E[u].cap -= f;E[u^1].cap += f;}}return -mincost;}int main(){int u, v, cap, w;while (cin >> n >> m){if (!n && !m)break;cnt = 0;memset(head, -1, sizeof(head));for (int i = 2; i <= n; i++){scanf("%d", &w);add_edge(i, n+1, INF, -w);}for (int i = 0; i < m; i++){scanf("%d%d%d%d", &u, &v, &cap, &w);add_edge(u, v, cap, w);add_edge(v, u, cap, w);}cout << mcmf(1, n+1, n+2) << endl;}return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.