Description
Like everyone else, cows like to stand close to their friends when queuing for feed. FJ has N (2 <= N <= 1,000) cows numbered 1..N standing along a straight line waiting for feed. The cows are standing in the same order as they are numbered, and since they can be rather pushy, it is possible that two or more cows can line up at exactly the same location (that is, if we think of each cow as being located at some coordinate on a number line, then it is possible for two or more cows to share the same coordinate).
Some cows like each other and want to be within a certain distance of each other in line. Some really dislike each other and want to be separated by at least a certain distance. A list of ML (1 <= ML <= 10,000) constraints describes which cows like each other and the maximum distance by which they may be separated; a subsequent list of MD constraints (1 <= MD <= 10,000) tells which cows dislike each other and the minimum distance by which they must be separated.
Your job is to compute, if possible, the maximum possible distance between cow 1 and cow N that satisfies the distance constraints.
【题目分析】
差分约束系统,f[i]表示到i的牛的总数,然后按照定义,跑一边bellman ford就可以了。
【代码】
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define inf 0x3f3f3f3f
using namespace std;
int h[20001],fr[20001],ne[20001],to[20001],w[20001],en=0,d[20001];
int n,m1,m2,m;
inline void add(int a,int b,int c)
{to[en]=b;ne[en]=h[a];fr[en]=a;w[en]=c;h[a]=en++;}
inline bool bfs()
{
memset(d,0x3f,sizeof d);
d[1]=0;
for (int i=1;i<n;++i)
for (int j=0;j<en;++j)
{
if (d[fr[j]]<inf&&d[fr[j]]+w[j]<d[to[j]])
d[to[j]]=d[fr[j]]+w[j];
}
// for (int i=1;i<=n;++i) cout<<d[i]<<endl;
for (int j=0;j<en;++j)
if (d[fr[j]]<inf&&d[fr[j]]+w[j]<d[to[j]]) return true;
return false;
}
int main()
{
cin>>n>>m1>>m2;m=m1+m2;
memset(h,-1,sizeof h);
for (int i=1;i<=m1;++i)
{
int a,b,c;
cin>>a>>b>>c;
if (a>b) swap(a,b);
add(a,b,c);
}
for (int i=1;i<=m2;++i)
{
int a,b,c;
cin>>a>>b>>c;
if (a>b) swap(a,b);
add(b,a,-c);
}
// for (int i=0;i<m;++i) cout<<fr[i]<<" "<<to[i]<<" "<<w[i]<<endl;
if (bfs()) cout<<"-1"<<endl;
else if (d[n]==inf) cout<<"-2"<<endl;
else cout<<d[n]<<endl;
}