题目大意
有 n n n 头编号为 1,2,…, n n n 的奶牛,它们按照编号顺序排成一排。有些奶牛是好基友,它们希望彼此之间的距离小于等于某个数。有些奶牛是情敌,它们希望彼此之间的距离大于等于某个数。给出 M L M_L ML 对的基友关系,它们希望距离在某个范围内。给出 M L M_L ML 对的情敌关系,它们希望距离在某个范围外。如果满足上述所有条件,1 号奶牛和 n n n 号奶牛之间的距离最大为多少。
分析
如果是基友关系,则满足 b − a ≤ x b-a\le x b−a≤x。如果是情敌关系则满足 c − d ≥ y c-d\ge y c−d≥y。全都转换成小于等于的情形,然后跑最短路即可。
思维点
如果给出两组关系:
4
−
1
≤
10
4-1\le10
4−1≤10,
3
−
2
≥
50
3-2\ge 50
3−2≥50。则一定产生矛盾。产生的图为:
这是不可能的。但我们在图中跑最短路,并不会发现这样的矛盾。因为,1 4 顶点与 2 3 顶点在图中表现出来是非连通的。因此,我们漏掉了一些图中顶点的关联信息:
2
−
1
≥
0
、
3
−
2
≥
0
、
4
−
3
≥
0
2-1\ge 0、3-2\ge 0、4-3\ge 0
2−1≥0、3−2≥0、4−3≥0。
示例程序
#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;
}