luogu2604 [ZJOI2010]网络扩容

先做一遍普通的dinic
然后再更改源点为超级源,超级源向原源加一条capacity=k && cost=0的边,再加上有费用的边跑最小费用最大流

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
int n, m, k, ss, tt, hea[1005], cnt, uu, vv, ww, xx, maxFlow, minCost, dis[1005], pre[1005];
const int oo=0x3f3f3f3f;
bool vis[1005];
queue<int> d;
struct Edge{
	int fro, nxt, too, val, cst, tmp;
}edge[20005];
void add_edge(int fro, int too, int val, int cst){
	edge[cnt].fro = fro;
	edge[cnt].nxt = hea[fro];
	edge[cnt].too = too;
	edge[cnt].val = val;
	edge[cnt].tmp = cst;
	edge[cnt].cst = 0;
	hea[fro] = cnt++;
}
void addEdge(int fro, int too, int val, int cst){
	add_edge(fro, too, val, cst);
	add_edge(too, fro, 0, -cst);
}
void qwq_edge(int fro, int too, int val, int cst){
	edge[cnt].nxt = hea[fro];
	edge[cnt].too = too;
	edge[cnt].val = val;
	edge[cnt].cst = cst;
	hea[fro] = cnt++;
}
void qwqEdge(int fro, int too, int val, int cst){
	qwq_edge(fro, too, val, cst);
	qwq_edge(too, fro, 0, -cst);
}
bool bfs(){
	memset(dis, 0, sizeof(dis));
	dis[ss] = 1;
	d.push(ss);
	while(!d.empty()){
		int x=d.front();
		d.pop();
		for(int i=hea[x]; i!=-1; i=edge[i].nxt){
			int t=edge[i].too;
			if(!dis[t] && edge[i].val>0){
				dis[t] = dis[x] + 1;
				d.push(t);
			}
		}
	}
	return dis[tt]!=0;
}
int dfs(int x, int lim){
	if(x==tt)	return lim;
	int addFlow=0;
	for(int i=hea[x]; i!=-1 && addFlow<lim; i=edge[i].nxt){
		int t=edge[i].too;
		if(dis[t]==dis[x]+1 && edge[i].val>0){
			int tmp=dfs(t, min(lim-addFlow, edge[i].val));
			edge[i].val -= tmp;
			edge[i^1].val += tmp;
			addFlow += tmp;
		}
	}
	return addFlow;
}
void dinic(){
	while(bfs())	maxFlow += dfs(ss, oo);
}
bool spfa(){
	memset(dis, 0x3f, sizeof(dis));
	memset(pre, -1, sizeof(pre));
	dis[ss] = 0;
	vis[ss] = true;
	d.push(ss);
	while(!d.empty()){
		int x=d.front();
		d.pop();
		vis[x] = false;
		for(int i=hea[x]; i!=-1; i=edge[i].nxt){
			int t=edge[i].too;
			if(dis[t]>dis[x]+edge[i].cst && edge[i].val>0){
				dis[t] = dis[x] + edge[i].cst;
				pre[t] = i;
				if(!vis[t]){
					vis[t] = true;
					d.push(t);
				}
			}
		}
	}
	return dis[tt]!=oo;
}
void mcmf(){
	while(spfa()){
		int tmp=oo;
		for(int i=pre[tt]; i!=-1; i=pre[edge[i^1].too])
			tmp = min(tmp, edge[i].val);
		for(int i=pre[tt]; i!=-1; i=pre[edge[i^1].too]){
			edge[i].val -= tmp;
			edge[i^1].val += tmp;
			minCost += tmp * edge[i].cst;
		}
	}
}
int main(){
	memset(hea, -1, sizeof(hea));
	cin>>n>>m>>k;
	ss = 1; tt = n;
	for(int i=1; i<=m; i++){
		scanf("%d %d %d %d", &uu, &vv, &ww, &xx);
		addEdge(uu, vv, ww, xx);
	}
	dinic();
	cout<<maxFlow<<" ";
	ss = 0;
	int tmp=cnt;
	qwqEdge(ss, 1, k, 0);
	for(int i=0; i<tmp; i+=2)
		qwqEdge(edge[i].fro, edge[i].too, oo, edge[i].tmp);
	mcmf();
	cout<<minCost<<endl;
	return 0;
}
posted @ 2018-01-15 15:53  poorpool  阅读(116)  评论(0编辑  收藏  举报