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

BZOJ:1877: [SDOI2009]晨跑

时间:2018-01-02 23:28:34      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:mini   +=   har   cst   std   sdoi   题解   cap   rom   

题解:

最小费用流;

拆点法;

#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;

const int maxn=1000;
const int inf=100000000;

int n,m;

int totn,s,t;
struct Edge{
	int from,to,cap,flow,cost;
};
vector<int>G[maxn];
vector<Edge>edges;
int addedge(int x,int y,int z,int w){
	Edge e;
	e.from=x;e.to=y;e.cap=z;e.flow=0;e.cost=w;
	edges.push_back(e);
	e.to=x;e.from=y;e.cap=0;e.flow=0;e.cost=-w;
	edges.push_back(e);
	int c=edges.size();
	G[x].push_back(c-2);
	G[y].push_back(c-1);
}

queue<int>q;
int inq[maxn];
int d[maxn];
int p[maxn];
int spfa(int &nowflow,int &nowcost){
	for(int i=1;i<=totn;++i){
		d[i]=inf;inq[i]=0;
	}
	d[s]=0;q.push(s);inq[s]=1;p[s]=0;
	while(!q.empty()){
		int x=q.front();q.pop();inq[x]=0;
		for(int i=0;i<G[x].size();++i){
			Edge e=edges[G[x][i]];
			if((e.cap>e.flow)&&(d[x]+e.cost<d[e.to])){
				d[e.to]=d[x]+e.cost;
				p[e.to]=G[x][i];
				if(!inq[e.to]){
					q.push(e.to);
					inq[e.to]=1;
				}
			}
		}
	}
	if(d[t]==inf)return 0;
	int f=inf,x=t;
	while(x!=s){
		Edge e=edges[p[x]];
		f=min(f,e.cap-e.flow);
		x=e.from;
	}
	nowflow+=f;nowcost+=f*d[t];
	x=t;
	while(x!=s){
		edges[p[x]].flow+=f;
		edges[p[x]^1].flow-=f;
		x=edges[p[x]].from;
	}
	return 1;
}

int Mcmf(){
	int flow=0,cost=0;
	while(spfa(flow,cost));
	printf("%d %d\n",flow,cost);
}

int minit(){
	for(int i=1;i<=n+n;++i)G[i].clear();
	edges.clear();
	while(!q.empty())q.pop();
}
	
int main(){
	scanf("%d%d",&n,&m);
	minit();
	while(m--){
		int x,y,z;
		scanf("%d%d%d",&x,&y,&z);
		addedge(x+n,y,1,z);
	}
	addedge(1,1+n,inf,0);
	addedge(n,n+n,inf,0);
	for(int i=2;i<=n-1;++i)addedge(i,i+n,1,0);
	totn=n+n;s=1;t=n+n;
	Mcmf();
	return 0;
}

  

BZOJ:1877: [SDOI2009]晨跑

标签:mini   +=   har   cst   std   sdoi   题解   cap   rom   

原文地址:https://www.cnblogs.com/zzyer/p/8179136.html

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