[费用流]Bzoj P1877 晨跑

Description

Elaxia最近迷恋上了空手道,他为自己设定了一套健身计划,比如俯卧撑、仰卧起坐等 等,不过到目前为止,他
坚持下来的只有晨跑。 现在给出一张学校附近的地图,这张地图中包含N个十字路口和M条街道,Elaxia只能从 一
个十字路口跑向另外一个十字路口,街道之间只在十字路口处相交。Elaxia每天从寝室出发 跑到学校,保证寝室
编号为1,学校编号为N。 Elaxia的晨跑计划是按周期(包含若干天)进行的,由于他不喜欢走重复的路线,所以 
在一个周期内,每天的晨跑路线都不会相交(在十字路口处),寝室和学校不算十字路 口。Elaxia耐力不太好,
他希望在一个周期内跑的路程尽量短,但是又希望训练周期包含的天 数尽量长。 除了练空手道,Elaxia其他时间
都花在了学习和找MM上面,所有他想请你帮忙为他设计 一套满足他要求的晨跑计划。

Input

第一行:两个数N,M。表示十字路口数和街道数。 
接下来M行,每行3个数a,b,c,表示路口a和路口b之间有条长度为c的街道(单向)。
N ≤ 200,M ≤ 20000。

Output

两个数,第一个数为最长周期的天数,第二个数为满足最长天数的条件下最短的路程长 度。

Sample Input

7 10
1 2 1
1 3 1
2 4 1
3 4 1
4 5 1
4 6 1
2 5 5
3 6 6
5 7 1
6 7 1

Sample Output

2 11

题解

  • 拆点费用流
  • 我们可以把一个点拆成i和i+n
  • 由于每个点只能到达一次,i向i+n连边,容量为1,费用为0
  • 然后按照题目描述的建图,从起点的i+n(出点)向终点的i(入点)连边,每条边的长度即为费用
  • 注意这里的边的容量也应该为1,因为有可能从1直接到n
  • 从源点向s+n连边,从n向汇点连边,容量都为INF,费用为0

代码

#include<cstdio>
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int N=1001;
const int inf=0x3f3f3f3f;
int n,m,S,cnt,last[N],t,dis[N],f[N],d[N],ans1,ans2,s,v[N],q[N];
struct edge{int from,to,c,w,next,op;}e[N*N*2];
queue<int> Q;
void insert(int u,int v,int x,int y)
{
	e[++cnt].from=u; e[cnt].to=v; e[cnt].c=x; e[cnt].w=y; e[cnt].next=last[u]; last[u]=cnt; e[cnt].op=cnt+1;
	e[++cnt].from=v; e[cnt].to=u; e[cnt].c=0; e[cnt].w=-y; e[cnt].next=last[v]; last[v]=cnt; e[cnt].op=cnt-1;
}
bool spfa()
{
	for (int i=s;i<=t;i++)
	{
		dis[i]=inf;
		v[i]=0;
	}
	int head=0,tail=1;
	q[1]=s; v[s]=1; dis[s]=0;
	while (head!=tail)
	{
		if (head==1000) head=0;
		head++;
		int now=q[head],i=last[now];
		while (i)
		{
			if (e[i].c&&dis[now]+e[i].w<dis[e[i].to])
			{
				dis[e[i].to]=dis[now]+e[i].w;
				d[e[i].to]=i;
				if (!v[e[i].to])
				{
					v[e[i].to]=1;
					if (tail==1000) tail=0;
					tail++;
					q[tail]=e[i].to;
				}
			}
			i=e[i].next;
		}
		v[now]=0;
	}
	if (dis[t]==inf) return 0;
	return 1;
}
void mcf()
{
	int mn=inf,x=t;
	while (d[x])
	{
		mn=min(mn,e[d[x]].c);
		x=e[d[x]].from;
	}
	ans1++;
	x=t;
	while (d[x])
	{
		e[d[x]].c-=mn;
		e[e[d[x]].op].c+=mn;
		ans2+=e[d[x]].w*mn;
		x=e[d[x]].from;
	}
}
int main()
{
	scanf("%d%d",&n,&m);
	s=1; t=n+n;
	for (int i=0;i<m;i++)
	{
		int u,v,c;
		scanf("%d%d%d",&u,&v,&c);
		insert(u+n,v,1,c);
	}
	for (int i=2;i<n;i++) insert(i,i+n,1,0);
	insert(s,s+n,inf,0); insert(n,t,inf,0);
	while (spfa()) mcf();
	printf("%d %d
",ans1,ans2);
	return 0;
}

  

原文地址:https://www.cnblogs.com/Comfortable/p/9211047.html