# hihoCoder #1515 : 分数调查（带权并查集）

### 输出

10 5 3
1 2 10
2 3 10
4 5 -10
5 6 -10
2 5 10
1 10
1 5
3 5

-1
20
0

#include<bits/stdc++.h>
#define N 100009
using namespace std;
const int INF = 0x3f3f3f3f;

int pre[N], d[N];

inline void q_read(int &num)
{
char ch; int f = 1;
while(true)
{
ch = getchar();
if(ch == '-') f = -1;
if(isdigit(ch))
{
num = ch - '0';
break;
}
}
while(ch = getchar(), isdigit(ch)) num = num*10+ch-'0';
num *= f;
}

int get_pre(int x)
{
if(x==pre[x]) return x;
int t = pre[x];
pre[x] = get_pre(pre[x]);
d[x] += d[t];
return pre[x];
}

void Union(int u, int v, int w)
{
int x = get_pre(u);
int y = get_pre(v);
if(x != y)
{
pre[x] = y;
d[x] = d[v] + w - d[u];
//d[u] = w+d[v];
}
}

void init(int n)
{
for(int i = 1; i <= n; i++) pre[i] = i;
memset(d, 0, sizeof(d));
}

int main()
{
int n, m, q, u, v, w;
init(n);
for(int i = 1; i <= m; i++)
{
Union(u, v, w);
}
while(q--)
{
int x = get_pre(u);
int y = get_pre(v);
if(x != y) puts("-1");
else printf("%d\n", d[u] - d[v]);
}
return 0;
}


©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客