| Time Limit: 1000MS | Memory Limit: 65536K | |
| Total Submissions: 9479 | Accepted: 4545 |
Description
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.
Input
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
Sample Input
4 2 1 1 3 10 2 4 20 2 3 3
Sample Output
27
Hint
There are 4 cows. Cows #1 and #3 must be no more than 10 units apart, cows #2 and #4 must be no more than 20 units apart, and cows #2 and #3 dislike each other and must be no fewer than 3 units apart.
The best layout, in terms of coordinates on a number line, is to put cow #1 at 0, cow #2 at 7, cow #3 at 10, and cow #4 at 27.
Source
题目大意
给出点之间的关系
某两个点的距离>=k
或者某两个点的距离<=k
求第一个点到最后一个点的可能的最远距离
是个差分约束问题
因为每个点在数轴上的位置d[i]满足
d[1]<=d[2]<=...<=d[n]
即d[i]<=d[i+1]
若d[x]<=d[y],距离>=k
则d[y]>=d[x]+k
即d[x]<=d[y]-k
若d[x]<=d[y],距离<=k
则d[y]<=d[x]+k
可以看出来很像最短路
所以建边后由1点到n点求最短路
若最短路不存在,则距离不可能满足所有点,-1
若找不到1到n的路径,则n可以为无限远,-2
否则最短路就是答案
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int m,t1,t2,n;
struct self
{
int y,w,nxt;
}s[44444];
int fst[1111];
int flag[1111];
int x,y,w;
void add(int x,int y,int w)
{
n++;
s[n].y=y;
s[n].w=w;
s[n].nxt=fst[x];
fst[x]=n;
}
int d[1111];
queue<int>q;
int tims[1111];
void spfa()
{
memset(d,0x3f,sizeof(d));
memset(flag,0,sizeof(flag));
memset(tims,0,sizeof(tims));
d[1]=0;
q.push(1);
tims[1]=1;
while(!q.empty())
{
int u=q.front();
q.pop();
flag[u]=0;
for(int e=fst[u];e!=-1;e=s[e].nxt)
{
int v=s[e].y;
if(d[v]>d[u]+s[e].w)
{
d[v]=d[u]+s[e].w;
if(!flag[v])
{
flag[v]=1;
q.push(v);
tims[v]++;
if(tims[v]>m)
{
printf("-1\n");
return;
}
}
}
}
}
if(d[m]==0x3f3f3f3f)
printf("-2\n");
else
printf("%d\n",d[m]);
return;
}
int main()
{
memset(fst,-1,sizeof(fst));
scanf("%d%d%d",&m,&t1,&t2);
for(int i=1;i<m;i++)
add(i+1,i,0);
for(int i=1;i<=t1;i++)
{
scanf("%d%d%d",&x,&y,&w);
add(x,y,w);
}
for(int i=1;i<=t2;i++)
{
scanf("%d%d%d",&x,&y,&w);
add(y,x,-w);
}
spfa();
return 0;
}
262




被折叠的 条评论
为什么被折叠?



