题目链接
第一问就是简单的最大流。
第二问,保留第一问求完最大流的残量网络。
然后新建一个源点,向原源点连一条流量为k,费用为0的边。
然后所有边重新连一起(原来的边保留),费用为题目所给,最小费用即为第二问答案,很好理解。
#include <cstdio>
#include <queue>
#include <cstring>
#define INF 2147483647
using namespace std;
const int MAXN = 1010;
const int MAXM = 20010;
struct Edge{
int from, next, to, rest, cost;
}e[MAXM];
int head[MAXN], num = 1, n, m, k;
inline void Add(int from, int to, int flow, int cost){
e[++num] = (Edge){from, head[from], to, flow, cost}; head[from] = num;
e[++num] = (Edge){to, head[to], from, 0, -cost}; head[to] = num;
}
int s, t, a[MAXM], b[MAXM], c[MAXM], d[MAXM], now, maxflow, mincost;
queue <int> q;
int v[MAXN], dis[MAXN], pre[MAXN], flow[MAXN];
int re(){
q.push(s);
memset(dis, 127, sizeof dis);
memset(flow, 0, sizeof flow);
dis[s] = 0; pre[t] = 0; flow[s] = INF;
while(q.size()){
now = q.front(); q.pop(); v[now] = 0;
for(int i = head[now]; i; i = e[i].next)
if(e[i].rest && dis[e[i].to] > dis[now] + e[i].cost){
dis[e[i].to] = dis[now] + e[i].cost;
pre[e[i].to] = i; flow[e[i].to] = min(flow[now], e[i].rest);
if(!v[e[i].to]) v[e[i].to] = 1, q.push(e[i].to);
}
}
return pre[t];
}
int main(){
scanf("%d%d%d", &n, &m, &k); s = 1; t = n;
for(int i = 1; i <= m; ++i){
scanf("%d%d%d%d", &a[i], &b[i], &c[i], &d[i]);
Add(a[i], b[i], c[i], 0);
}
while(re()){
now = pre[t];
while(now){
e[now].rest -= flow[t];
e[now ^ 1].rest += flow[t];
now = pre[e[now].from];
}
maxflow += flow[t];
}
printf("%d ", maxflow);
s = 0; Add(s, 1, k, 0);
for(int i = 1; i <= m; ++i)
Add(a[i], b[i], INF, d[i]);
while(re()){
now = pre[t];
while(now){
e[now].rest -= flow[t];
e[now ^ 1].rest += flow[t];
mincost += e[now].cost * flow[t];
now = pre[e[now].from];
}
}
printf("%d
", mincost);
return 0;
}