codevs1242 布局

题目描述 Description

当排队等候喂食时,奶牛喜欢和它们的朋友站得靠近些。FJ有N(2<=N<=1000)头奶牛,编号从1到N,沿一条直线站着等候喂食。奶牛排在队伍中的顺序和它们的编号是相同的。因为奶牛相当苗条,所以可能有两头或者更多奶牛站在同一位置上。即使说,如果我们想象奶牛是站在一条数轴上的话,允许有两头或更多奶牛拥有相同的横坐标。

一些奶牛相互间存有好感,它们希望两者之间的距离不超过一个给定的数L。另一方面,一些奶牛相互间非常反感,它们希望两者间的距离不小于一个给定的数D。给出ML条关于两头奶牛间有好感的描述,再给出MD条关于两头奶牛间存有反感的描述。(1<=ML , MD<=10000,1<=L,D<=1000000)

你的工作是:如果不存在满足要求的方案,输出-1;如果1号奶牛和N号奶牛间的距离可以任意大,输出-2;否则,计算出在满足所有要求的情况下,1号奶牛和N号奶牛间可能的最大距离。

输入描述 Input Description

Line 1: Three space-separated integers: N, ML, and MD.

Lines 2..ML+1: Each line contains three space-separated positive integers: A, B, and D, with 1 <= A < B <= N. Cows A and B must be at most D (1 <= D <= 1,000,000) apart.

Lines ML+2..ML+MD+1: Each line contains three space-separated positive integers: A, B, and D, with 1 <= A < B <= N. Cows A and B must be at least D (1 <= D <= 1,000,000) apart.

输出描述 Output Description

Line 1: A single integer. If no line-up is possible, output -1. If cows 1 and N can be arbitrarily far apart, output -2. Otherwise output the greatest possible distance between cows 1 and N.

样例输入 Sample Input

4 2 1

1 3 10

2 4 20

2 3 3

样例输出 Sample Output

27

题解

看网上有一篇差分约束写的不错:http://www.cppblog.com/menjitianya/archive/2015/11/19/212292.html

然后进入正题,这道题算是差分约束很裸的题了,用spfa判负权圈,注意不等号方向统一

代码

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath> 
#define N 100050
using namespace std; 

int n,ml,md; 
int q[10*N],flag[N],dis[N],cnt[N];
bool f;

int a[N],b[N],w[N],nt[N],p[N],num;
void add(int x,int y,int v)
{
	a[++num]=x;b[num]=y;w[num]=v;
	nt[num]=p[x];p[x]=num;
}

void read()
{
	scanf("%d%d%d",&n,&ml,&md);
	for(int i=1;i<=ml;i++)
	{
		int x,y,v;scanf("%d%d%d",&x,&y,&v);
		add(x,y,v);
	}
	for(int i=1;i<=md;i++)
	{
		int x,y,v;scanf("%d%d%d",&x,&y,&v);
		add(y,x,-v);
	}
}

void spfa()
{
	memset(dis,127,sizeof(dis));
	dis[1]=0;flag[1]=1;q[1]=1;cnt[1]++;
	int head=0,tail=1;
	while(head<tail)
	{
		int k=q[++head];
		for(int e=p[k];e;e=nt[e])
		{
			int kk=b[e];
			if(dis[kk]-dis[k]>w[e])
			{
				dis[kk]=dis[k]+w[e];
				if(!flag[kk])
				{
					flag[kk]=1;
					cnt[kk]++;
					if(cnt[kk]>=n) {f=1;break;}
					q[++tail]=kk; 
				}
			}
		}
		flag[k]=0;
		if(f) break;
	}
}

int main()
{
	read();
	spfa();
	if(f) printf("-1");
	else if(dis[n]>1000000) printf("-2");
	else printf("%d",dis[n]);
	return 0;
}
posted @ 2017-08-16 13:19  XYZinc  阅读(227)  评论(0编辑  收藏  举报