当排队等候喂食时,奶牛喜欢和它们的朋友站得靠近些。农夫约翰有 NN
头奶牛,编号从 11
到 NN
,沿一条直线站着等候喂食。奶牛排在队伍中的顺序和它们的编号是相同的。因为奶牛相当苗条,所以可能有两头或者更多奶牛站在同一位置上。如果我们想象奶牛是站在一条数轴上的话,允许有两头或更多奶牛拥有相同的横坐标。一些奶牛相互间存有好感,它们希望两者之间的距离不超过一个给定的数 LL
。另一方面,一些奶牛相互间非常反感,它们希望两者间的距离不小于一个给定的数 DD
。给出 MLML
条关于两头奶牛间有好感的描述,再给出 MDMD
条关于两头奶牛间存有反感的描述。你的工作是:如果不存在满足要求的方案,输出-1;如果 11
号奶牛和 NN
号奶牛间的距离可以任意大,输出-2;否则,计算出在满足所有要求的情况下,11
号奶牛和 NN
扫描二维码关注公众号,回复:
10949740 查看本文章
号奶牛间可能的最大距离。输入格式第一行包含三个整数 N,ML,MDN,ML,MD
。接下来 MLML
行,每行包含三个正整数 A,B,LA,B,L
,表示奶牛 AA
和奶牛 BB
至多相隔 LL
的距离。再接下来 MDMD
行,每行包含三个正整数 A,B,DA,B,D
,表示奶牛 AA
和奶牛 BB
至少相隔 DD
的距离。输出格式输出一个整数,如果不存在满足要求的方案,输出-1;如果 11
号奶牛和 NN
号奶牛间的距离可以任意大,输出-2;否则,输出在满足所有要求的情况下,11
号奶牛和 NN
号奶牛间可能的最大距离。数据范围2≤N≤10002≤N≤1000
,
1≤ML,MD≤1041≤ML,MD≤104
,
1≤L,D≤1061≤L,D≤106
输入样例:4 2 1
1 3 10
2 4 20
2 3 3
输出样例:27
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1010, M = 10000 + 10000 + 1000 + 10, INF = 0x3f3f3f3f;
int n, m1, m2;
int h[N], e[M], w[M], ne[M], idx;
int dist[N];
int q[N], cnt[N];
bool st[N];
void add(int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}
bool spfa(int size)
{
int hh = 0, tt = 0;
memset(dist, 0x3f, sizeof dist);
memset(st, 0, sizeof st);
memset(cnt, 0, sizeof cnt);
for (int i = 1; i <= size; i ++ )
{
q[tt ++ ] = i;
dist[i] = 0;
st[i] = true;
}
while (hh != tt)
{
int t = q[hh ++ ];
if (hh == N) hh = 0;
st[t] = false;
for (int i = h[t]; ~i; i = ne[i])
{
int j = e[i];
if (dist[j] > dist[t] + w[i])
{
dist[j] = dist[t] + w[i];
cnt[j] = cnt[t] + 1;
if (cnt[j] >= n) return true;
if (!st[j])
{
q[tt ++ ] = j;
if (tt == N) tt = 0;
st[j] = true;
}
}
}
}
return false;
}
int main()
{
scanf("%d%d%d", &n, &m1, &m2);
memset(h, -1, sizeof h);
for (int i = 1; i < n; i ++ ) add(i + 1, i, 0);
while (m1 -- )
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
if (a > b) swap(a, b);
add(a, b, c);
}
while (m2 -- )
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
if (a > b) swap(a, b);
add(b, a, -c);
}
if (spfa(n)) puts("-1");
else
{
spfa(1);
if (dist[n] == INF) puts("-2");
else printf("%d\n", dist[n]);
}
return 0;
}