https://blog.csdn.net/yjr3426619/article/details/82315133
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
const int maxN = 100005;
int parent[maxN];
int score[maxN];
int find(int x)
{
if (x != parent[x])
{
int t = parent[x];
parent[x] = find(parent[x]);
score[x] += score[t];
}
return parent[x];
}
int main()
{
int n, m, q;
scanf("%d%d%d", &n, &m, &q);
for (int i = 1 ; i <= n ; i ++ )
{
parent[i] = i;
}
while ( m-- )
{
int x, y, s;
scanf("%d%d%d", &x, &y, &s);
int px = find(x);
int py = find(y);
if (px != py)
{
parent[px] = py;
score[px] = -score[x] + score[y] + s;
}
}
while ( q -- )
{
int x, y;
scanf("%d%d",&x,&y);
if (find(x) != find(y))
{
printf("-1\n");
}
else {
printf("%d\n", score[x] - score[y]);
}
}
return 0;
}