码迷,mamicode.com
首页 > 其他好文 > 详细

luogu2153 [SDOI2009]晨跑

时间:2018-01-03 11:44:58      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:blog   cout   const   i++   include   ret   space   while   pre   

要想限制流量,总要想着拆点。

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
int n, m, ss, tt, uu, vv, ww, maxFlow, minCost, cnt, hea[405], pre[405];
int dis[405];
const int oo=0x3f3f3f3f;
queue<int> d;
bool vis[405];
struct Edge{
	int too, nxt, val, cst;
}edge[50005];
void add_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 addEdge(int fro, int too, int val, int cst){
	add_edge(fro, too, val, cst);
	add_edge(too, fro, 0, -cst);
}
bool bfs(){
	memset(pre, -1, sizeof(pre));
	memset(dis, 0x3f, sizeof(dis));
	dis[ss] = 0;
	d.push(ss);
	vis[ss] = true;
	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){
				pre[t] = i;
				dis[t] = dis[x] + edge[i].cst;
				if(!vis[t]){
					vis[t] = true;
					d.push(t);
				}
			}
		}
	}
	return dis[tt]!=oo;
}
void dinic(){
	while(bfs()){
		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;
		}
		maxFlow += tmp;
	}
}
int main(){
	memset(hea, -1, sizeof(hea));
	cin>>n>>m;
	ss = 1; tt = n * 2;
	for(int i=1; i<=n; i++)
		if(i!=1 && i!=n)	addEdge(i, i+n, 1, 0);
		else	addEdge(i, i+n, oo, 0);
	for(int i=1; i<=m; i++){
		scanf("%d %d %d", &uu, &vv, &ww);
		addEdge(uu+n, vv, 1, ww);
	}
	dinic();
	cout<<maxFlow<<" "<<minCost<<endl;
	return 0;
}

luogu2153 [SDOI2009]晨跑

标签:blog   cout   const   i++   include   ret   space   while   pre   

原文地址:https://www.cnblogs.com/poorpool/p/8182063.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!