题意:N个人排成一条线,按顺序编号1到N,有可能多个人站在一个点上。有x个约束(a,b,c),表示a和b互有好感,他俩的距离不能超过c,还有y个约束(a,b,c),表示a和b互相讨厌,他俩的距离不能少于c。求1到N的最大距离,无解输出-1,有无穷远输出-2.
思路:差分约束裸题,建图跑最短路就行,以1为起点,N为终点。如果dis[N]为inf,说明两个数字互不影响,就返回-2。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <stack>
#include <cmath>
#include <list>
#include <cstdlib>
#include <set>
#include <string>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int maxn = 1005;
struct edg{
int v, nxt, w;
}G[maxn * 21];
int tot, pre[maxn];
int n, times[maxn], dis[maxn];
bool vis[maxn];
void add(int u, int v, int w) {
G[tot].v = v;
G[tot].w = w;
G[tot].nxt = pre[u];
pre[u] = tot++;
}
int spfa() {
memset(dis, 0x3f, sizeof(dis));
memset(vis, 0, sizeof(vis));
memset(times, 0, sizeof(times));
queue<int> que;
que.push(1);
vis[1] = true;
dis[1] = 0;
times[1] = 1;
while (!que.empty()) {
int u = que.front();
que.pop();
vis[u] = false;
for (int i = pre[u]; ~i; i = G[i].nxt) {
int v = G[i].v, w = G[i].w;
if (dis[u] + w < dis[v]) {
dis[v] = dis[u] + w;
if (!vis[v]) {
if (++times[v] > n) {
return -1;
}
vis[v] = true;
que.push(v);
}
}
}
}
return dis[n] == inf ? -2 : dis[n];
}
int main(){
int x, y, a, b, c, t;
scanf("%d", &t);
while (t--) {
scanf("%d%d%d", &n, &x, &y);
tot = 0;
memset(pre, -1, sizeof(pre));
for (int i = 1; i < n; ++i) {
add(i + 1, i, 0);
}
while (x--) {
scanf("%d%d%d", &a, &b, &c);
add(a, b, c);
}
while (y--) {
scanf("%d%d%d", &a, &b, &c);
add(b, a, -c);
}
printf("%d\n", spfa());
}
return 0;
}