【ZJOI2010】网络扩容

时间:2023-12-10 20:18:08

费用流+最大流
先一遍最大流
再所有边扩容,新加节点限制扩容量k


# include <bits/stdc++.h>
# define IL inline
# define RG register
# define Fill(a, b) memset(a, b, sizeof(a))
# define Copy(a, b) memcpy(a, b, sizeof(a))
# define ID(a, b) n * (a - 1) + b
using namespace std;
typedef long long ll;
const int _(5010), __(2e5 + 10), INF(2147483647); IL ll Read(){
RG char c = getchar(); RG ll x = 0, z = 1;
for(; c < '0' || c > '9'; c = getchar()) z = c == '-' ? -1 : 1;
for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
return x * z;
} int n, m, k, fst[_], nxt[__], to[__], cnt, w[__], cost[__];
int ff[__], tt[__], ww[__], cc[__];
int S, T, max_flow, min_cost, dis[_], pv[_], pe[_], vis[_];
queue <int> Q; IL void Add(RG int u, RG int v, RG int f, RG int co){
cost[cnt] = co; w[cnt] = f; to[cnt] = v; nxt[cnt] = fst[u]; fst[u] = cnt++;
cost[cnt] = -co; w[cnt] = 0; to[cnt] = u; nxt[cnt] = fst[v]; fst[v] = cnt++;
} IL bool Bfs(){
Fill(dis, 127); dis[S] = 0; vis[S] = 1; Q.push(S);
while(!Q.empty()){
RG int u = Q.front(); Q.pop();
for(RG int e = fst[u]; e != -1; e = nxt[e])
if(w[e] && dis[to[e]] > dis[u] + cost[e]){
dis[to[e]] = dis[u] + cost[e];
pe[to[e]] = e; pv[to[e]] = u;
if(!vis[to[e]]) vis[to[e]] = 1, Q.push(to[e]);
}
vis[u] = 0;
}
if(dis[T] >= dis[T + 1]) return 0;
RG int ret = INF;
for(RG int u = T; u != S; u = pv[u]) ret = min(ret, w[pe[u]]);
min_cost += ret * dis[T]; max_flow += ret;
for(RG int u = T; u != S; u = pv[u]) w[pe[u]] -= ret, w[pe[u] ^ 1] += ret;
return 1;
} int main(RG int argc, RG char* argv[]){
Fill(fst, -1); n = Read(); m = Read(); k = Read(); S = 1; T = n;
for(RG int i = 1; i <= m; i++) ff[i] = Read(), tt[i] = Read(), cc[i] = Read(), ww[i] = Read();
for(RG int i = 1; i <= m; i++) Add(ff[i], tt[i], cc[i], 0);
while(Bfs()); printf("%d", max_flow);
for(RG int i = 1; i <= m; i++) Add(ff[i], tt[i], k, ww[i]);
T = n + 1; Add(n, T, k, 0);
for(min_cost = 0; Bfs(); ); printf(" %d\n", min_cost);
return 0;
}