[洛谷P2153] [SDOI2009]晨跑(费用流)

典型的最小费用最大流。只要把一个点拆成两个,中间连一条容量1费用0的边来限制每个点只用一次就好。

要注意第1个点和第n个点不用限制次数,以及从1到n的边容量为1。

#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
const int N=410,M=30010,inf=0x7fffffff;
struct edge{
	int y,next,f,c;
}data[M*2];
int n,m,s,t,num,h[N],cost[N],pre[N],path[N],fmax[N];
bool vis[N];
queue<int> q;
inline int read(){
	int x=0,f=0;
	char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')f=1;ch=getchar();}
	while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
	return f?-x:x;
}
inline void add(int x,int y,int f,int c){
	data[++num].y=y;data[num].f=f;data[num].c=c;
	data[num].next=h[x];h[x]=num;
	data[++num].y=x;data[num].f=0;data[num].c=-c;
	data[num].next=h[y];h[y]=num;
}
bool spfa(int s,int t){
	memset(cost,0x3f,sizeof cost);
	memset(vis,false,sizeof vis);
	while(!q.empty())q.pop();
	q.push(s);cost[s]=0;vis[s]=true;fmax[s]=inf;pre[t]=-1;
	while(!q.empty()){
		int u=q.front();q.pop();vis[u]=false;
		for(int i=h[u];i!=-1;i=data[i].next){
			int v=data[i].y;
			if(data[i].f>0&&cost[v]>cost[u]+data[i].c){
				cost[v]=cost[u]+data[i].c;
				pre[v]=u;path[v]=i;
				fmax[v]=min(data[i].f,fmax[u]);
				if(!vis[v]){vis[v]=true;q.push(v);}
			}
		}
	}
	return pre[t]!=-1;
}
void mcmf(int s,int t){
	int flow=0,charge=0;
	while(spfa(s,t)){
		flow+=fmax[t];
		charge+=cost[t]*fmax[t];
		for(int i=t;i!=s;i=pre[i]){
			data[path[i]].f-=fmax[t];
			data[path[i]^1].f+=fmax[t];
		}
	}
	printf("%d %d",flow,charge);
}
int main(){
	n=read();m=read();s=1;t=2*n;
	memset(h,-1,sizeof h);num=-1;
	add(1,1+n,inf,0);add(n,n*2,inf,0);
	for(int i=2;i<n;i++)add(i,i+n,1,0);
	for(int x,y,c,i=1;i<=m;i++){
		x=read();y=read();c=read();
		if(x==1&&y==n)add(1+n,n,1,c);
		else add(x+n,y,inf,c);
	}
	mcmf(s,t);
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值