网络扩容
题目链接
https://www.luogu.org/problemnew/show/P2604
题解
对于每条边u→vu \rightarrow vu→v,我们将按照容量=C=C=C,费用=0=0=0建边,这些算是免费边.
然后我们再对同一对点u,vu,vu,v建立一条容量为INFINFINF,费用为扩容费用WWW的边,这些边算是扩容流量要走的边,有费用.
跑一边MCMFMCMFMCMF即可.
代码
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#define pr(x) std::cout << #x << ':' << x << std::endl
#define rep(i,a,b) for(int i = a;i <= b;++i)const int inf = 0x3f3f3f3f;
const int mm = 111111;
const int maxn = 1111;
int node,src,dest,edge;
int ver[mm],flow[mm],cst[mm],nxt[mm];
int head[maxn],work[maxn],dis[maxn],q[maxn];
int tot_cost;
void prepare(int _node,int _src,int _dest)
{node=_node,src=_src,dest=_dest;for(int i=0; i<node; ++i)head[i]=-1;edge=0;tot_cost = 0;
}
void add_edge(int u,int v,int c,int cost)
{ver[edge]=v,flow[edge]=c,nxt[edge]=head[u],cst[edge]=cost,head[u]=edge++;ver[edge]=u,flow[edge]=0,nxt[edge]=head[v],cst[edge]=-cost,head[v]=edge++;
}
int ins[maxn];
int pre[maxn];
bool Dinic_spfa()
{memset(ins,0,sizeof(ins));memset(dis,inf,sizeof(dis));memset(pre,-1,sizeof(pre));std::queue<int> Q;Q.push(src);dis[src] = 0,ins[src] = 1;pre[src] = -1;while(!Q.empty()){int u = Q.front();Q.pop();ins[u] = 0;for(int e = head[u];e != -1;e = nxt[e]){int v = ver[e];if(!flow[e]) continue;if(dis[v] > dis[u] + cst[e]){dis[v] = dis[u] + cst[e];pre[v] = e;if(!ins[v]) ins[v] = 1,Q.push(v);}}}return dis[dest] < inf;
}
int Dinic_flow()
{int i,ret=0,delta=inf;while(Dinic_spfa()){for(int i=pre[dest];i != -1;i = pre[ver[i^1]])delta = std::min(delta,flow[i]);for(int i=pre[dest];i != -1;i = pre[ver[i^1]])flow[i] -= delta,flow[i^1] += delta;ret+=delta;tot_cost += dis[dest]*delta;}return ret;
}
const int N = 5010;
int n,m,k;
int u[N],v[N],c[N],w[N];
int main() {std::cin >> n >> m >> k;for(int i = 1;i <= m;++i) {std::cin >> u[i] >> v[i] >> c[i] >> w[i];} prepare(n,0,n-1);for(int i = 1;i <= m;++i) {add_edge(u[i]-1,v[i]-1,c[i],0);}int pf = Dinic_flow();std::cout << pf << " ";prepare(n+1,0,n);for(int i = 1;i <= m;++i) {add_edge(u[i],v[i],c[i],0);add_edge(u[i],v[i],inf,w[i]);}add_edge(0,1,pf+k,0);Dinic_flow();std::cout << tot_cost << std::endl;return 0;
}