mysql最小費用最大流問題 最小費用最大流問題

2021-10-19 19:37:49 字數 2628 閱讀 7521

最小費用最大流就是在原來求最大流的基礎上,假設每條邊還有乙個單位流量所需要的費用,因為最小費用的出現,原本的平行邊變得有意義,並且允許反向增廣,基本上就是將原本bfs改為進行一次bellmanford演算法尋找最短路徑,只要初始流是該流量下的最小費用可行流,每次增廣後的新流都是新流量下的最小費用流。下面poj2135的題解:

題意:從起點出發,走到終點再回到起點,每條邊都對應乙個時間,求所需的最短時間。

要點:這題乍一看很像最短路徑,但其實是乙個最小費用最大流,可以等效為從起點到終點兩次,這兩次走過的邊沒有交集,所以把每條邊對應的容量改為1,這樣確保只能走一次,再加入乙個超級源和乙個超級匯,它們對應的容量為2。

accepted

1496k

172ms

1899b

2016-08-18 18:30:13#include

#include

#include

#include

using namespace std;

const int n = 1050;

const int inf = 0x3f3f3f3f;//這個值要夠大,否則會wa

struct edge

int from, to, flow, cap, cost;

bool vis[n];

int p[n], a[n], d[n];

vector g[n];//鄰接表,g[i][j]表示結點i的第j條邊在edges陣列中儲存的下標

vector edges;

void init(int n)

for (int i = 0; i <= n; i++)

g[i].clear();

edges.clear();

void addedge(int from, int to, int cap, int cost)

edge temp1 = ;

edge temp2 = ;//允許反向增廣

edges.push_back(temp1);

edges.push_back(temp2);

int len = edges.size();

g[from].push_back(len - 2);

g[to].push_back(len - 1);

bool bellmanford(int s, int t,int &flow,int &cost)

for (int i = 0; i < n; i++)

d[i] = inf;//這裡一開始用memset結果出錯,除錯了半天才找出來

d[s] = 0;

memset(vis,false, sizeof(vis));

memset(p, -1, sizeof(p));

p[s] = -1;

a[s] = inf;

queue que;

que.push(s);

vis[s] = true;

while (!que.empty())

int u = que.front();

que.pop();

vis[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 (!vis[e.to])

que.push(e.to);

vis[e.to] = true;

if (d[t] == inf)

return false;

flow += a[t];

cost += d[t] * a[t];

for (int i = t; i != s; i = edges[p[i]].from)

edges[p[i]].flow += a[t];

edges[p[i]^1].flow -= a[t];

return true;

int mincost(int s, int t)

int flow = 0, cost = 0;

while (bellmanford(s, t, flow, cost))

continue;

return cost;

int main()

int n,m;

while (cin >> n >> m)

init(n+1);

int u, v, w;

for (int i = 0; i < m; i++)

cin >> u >> v >> w;

addedge(u, v, 1, w);

addedge(v, u, 1, w);//題目中是無向圖

addedge(0, 1, 2, 0);

addedge(n, n + 1, 2, 0);

int ans = mincost(0, n + 1);

cout << ans << endl;

return 0;

mysql最小費用最大流問題 最小費用最大流問題

複雜網路中,單源單點的最小費用最大流演算法 mcmf 應用廣泛。在實際網路問題中,不僅考慮從 vs到 vt的流量最大,還要考慮可行流在網路傳送過程中的費用問題,這就是網路的最小費用最大流問題。最小費用最大流問題的一般提法 已知容量網路 d v a c 每條弧 vi,vj 除了已給出容量 cij 外,...

mysql最小費用最大流問題 最小費用最大流

最小費用最大流 修改的dijkstra ford fulksonff演算法 修改的dijkstra其實和johnson演算法的思想是一致的。乙個求最小費用最大流的樸素演算法是這樣的 1求最小費用增廣路2判斷是否存在增廣路,否的話演算法終止。3增加增廣路上邊的流量4在增廣路上新增必要的逆向負權邊5go...

最小費用最大流問題

網路流相關知識參考 出處 優you 大致題意 給定乙個n m的地圖,地圖上有若干個man和house,且man與house的數量一致。man每移動一格需花費 1 即單位費用 單位距離 一間house只能入住乙個man。現在要求所有的man都入住house,求最小費用。解題思路 費用流問題。構圖 把m...