BZOJ:1877: [SDOI2009]晨跑

Posted zzyer

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了BZOJ:1877: [SDOI2009]晨跑相关的知识,希望对你有一定的参考价值。

题解:

最小费用流;

拆点法;

#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]晨跑的主要内容,如果未能解决你的问题,请参考以下文章

BZOJ1877: [SDOI2009]晨跑

BZOJ 1877 [SDOI2009]晨跑

BZOJ 1877SDOI 2009晨跑

BZOJ:1877: [SDOI2009]晨跑

BZOJ1877:[SDOI2009]晨跑——题解

费用流BZOJ1877[SDOI2009]-晨跑