越流越贵(最小费用最大流)
Posted jpphy0
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了越流越贵(最小费用最大流)相关的知识,希望对你有一定的参考价值。
问题
分析
代码
#include<bits/stdc++.h>
using namespace std;
const int MXN = 55, MXE = 510, inf = 0x3f3f3f3f;
int n, m, pre[MXN], dis[MXN], inq[MXN], flow[MXN];
int head[MXN], tot;
struct Edge{int to, nxt, cap, cost;}edge[MXE<<5];
void addEdge(int u, int v, int cap, int cost){
Edge &e = edge[++tot];
e.to = v, e.cap = cap, e.cost = cost, e.nxt = head[u], head[u] = tot;
}
void add(int u, int v, int cap, int cost){
addEdge(u, v, cap, cost), addEdge(v, u, 0, -cost);
}
bool spfa(){
memset(inq, 0, sizeof inq);
memset(flow, inf, sizeof flow);
memset(dis, inf, sizeof dis);
queue<int> q;
q.push(1), inq[1] = 1, dis[1] = 0, flow[1] = inf;
int from, to;
while(q.size()){
from = q.front(), q.pop(), inq[from] = 0;
for(int i = head[from]; ~i; i = edge[i].nxt){
if(edge[i].cap == 0) continue;
to = edge[i].to;
if(dis[to] > dis[from]+edge[i].cost){
dis[to] = dis[from]+edge[i].cost;
if(!inq[to]) q.push(to), inq[to] = 1;
pre[to] = i;
flow[to] = min(flow[from], edge[i].cap);
}
}
}
return dis[n] != inf;
}
void update(int s, int t){
for(int i, now = n; now != s; now = edge[i^1].to)
i = pre[now], edge[i].cap -= flow[now], edge[i^1].cap += flow[now];
}
int main(){
int t, u, v, c, maxflow, ans;
scanf("%d", &t);
while(t--){
maxflow = 0, ans = 0, tot = 1;
memset(head, -1, sizeof head);
scanf("%d%d", &n, &m);
for(int i = 1; i <= m; ++i){
scanf("%d%d%d", &u, &v, &c);
for(int j = 1; j<= c; ++j) add(u, v, 1, 2*j-1);
}
while(spfa()) maxflow += flow[n], ans += flow[n]*dis[n], update(1, n);
printf("%d %d\\n", maxflow, ans);
}
return 0;
}
以上是关于越流越贵(最小费用最大流)的主要内容,如果未能解决你的问题,请参考以下文章