排队布局
分析
- \(第一问问是否存在负环,将n个点全放进队列即可\)
- \(如何判断1到N的距离可以无限大?\)
约束关系
- \(x_b\le x_a+L\)
- \(x_b-x_a\ge D\Rightarrow x_a\le x_b-D\)
- \(x_i\le x_{i+1}\)
代码
#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define pb push_back
#define PII pair<int, int>
#define x first
#define y second
#define inf 0x3f3f3f3f
const int N = 1010, M = 10000 + 10000 + 1000 + 10;
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, ne[idx] = h[a], w[idx] = c, 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] += 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() {
IO;
cin >> 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;
cin >> a >> b >> c;
if (a > b) swap(a, b);
add(a, b, c);
}
while (m2--) {
int a, b, c;
cin >> 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 cout << dist[n] << '\n';
}
return 0;
}