题目
代码(正确性未知)
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
int dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1};
const double eps = 1e-8;
const int N = 1e5 + 10, M = 2 * N;
int n, m, q;
int h[N], e[M], ne[M], idx;
LL w[M];
bool st[N];
unordered_map<int, LL> S;
int p[N];
void add(int a, int b, LL c)
{
e[idx] = b;
ne[idx] = h[a];
w[idx] = c;
h[a] = idx++;
}
int find(int x)
{
if (p[x] != x)
p[x] = find(p[x]);
return p[x];
}
void bfs(int u)
{
S[u] = 0;
st[u] = true;
queue<int> q;
q.push(u);
while (q.size())
{
int t = q.front();
q.pop();
for (int i = h[t]; i != -1; i = ne[i])
{
int j = e[i];
if (!st[j])
{
st[j] = true;
S[j] = S[t] + w[i];
q.push(j);
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
memset(h, -1, sizeof h);
cin >> n >> m >> q;
for (int i = 0; i <= n; i++)
{
p[i] = i;
}
while (m--)
{
int a, b;
LL c;
cin >> a >> b >> c;
// b - (a - 1) = c
add(a - 1, b, c);
add(b, a - 1, -c);
int pa = find(a - 1), pb = find(b);
if (pa != pb)
p[pa] = pb;
}
for (int i = 0; i <= n; i++)
{
if (!st[i])
bfs(i);
}
while (q--)
{
int l, r;
cin >> l >> r;
if (find(l - 1) != find(r))
cout << "UNKNOWN\n";
else
{
cout << S[r] - S[l - 1] << '\n';
}
}
return 0;
}