費用流偽代碼
阿新 • • 發佈:2017-07-11
pre 要求 bsp 最小費用最大流 nbsp nod 設置 最大 while
代碼中求的是最小費用最大流,求最大費用最大流只需要在設置邊權時設置為原權值的相反數,執行一次最小費用最大流,計算得出最小費用的相反數就是要求的最大費用。
u[x], v[x], w[x], c[x] 分別表示 x 號邊的出發點,到達點,權值和殘量。
1 int SPFA() 2 { 3 int head, tail, i, node, p; 4 for (i = 1; i <= ver; ++i) { 5 dis[i] = INF; 6 path[i] = 0; 7 bok[i] = false; 8 }9 dis[s] = 0; 10 head = tail = 1; 11 que[tail++] = s; 12 bok[s] = true; 13 while (head < tail) { 14 node = que[head++]; 15 bok[node] = false; 16 for (p = fst[node]; p; p = nxt[p]) { 17 if (c[p] <= 0 || dis[node] + w[p] >= dis[v[p]]) 18 continue; 19 dis[v[p]] = dis[node] + w[p]; 20 path[v[p]] = p 21 if (bok[v[p]]) 22 continue; 23 que[tail++] = v[p]; 24 bok[v[p]] = true; 25 } 26 } 27 return dis[t]; 28 } 29 void modify() 30 { 31 int tmp = INF; 32 for(p = path[t]; p; p = path[u[p]]) 33 tmp = min(c[p], tmp); 34 cost += tmp * dis[t]; 35 maxflow += tmp; 36 for (p = path[t]; p; p = path[u[p]]) { 37 c[p] -= tmp; 38 c[p + 1] += tmp; 39 } 40 return ; 41 } 42 43 int main() 44 { 45 /* input */ 46 while (SPFA() < INF) 47 modify(); 48 /* now we get ‘cost‘ and ‘maxflow‘ */ 49 return 0; 50 }
費用流偽代碼