文章推荐:点击查看
用val[x]存放x与根节点的差。
感觉带权并查集的find函数跟merge函数有很多递归回溯的思想。
还有大佬说向量偏移之类的,我觉得应该就是利用关系之间的传递性。
AC代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5;
int n, m, q, x, y, s;
int pre[N], val[N];
void init();
int find(int x);
void merge(int x, int y, int s);
int main(int argc, char const *argv[])
{
scanf("%d %d %d", &n, &m, &q);
init();
while(m--){
scanf("%d %d %d", &x, &y, &s);
merge(x, y, s);
}
while(q--){
scanf("%d %d", &x, &y);
if(find(x) == find(y)) printf("%d\n", val[x] - val[y]);
else printf("-1\n");
}
return 0;
}
void init(){
memset(val, 0, sizeof val);
for(int i = 0; i <= n; ++i) pre[i] = i;
}
int find(int x){
if(pre[x] == x) return x;
int tem = find(pre[x]);
val[x] += val[pre[x]];
return pre[x] = tem;
}
void merge(int x, int y, int s){
int fx = find(x);
int fy = find(y);
if(fx != fy){
val[fy] = val[x] - val[y] - s;
pre[fy] = fx;
} else{
val[x] = val[y] + s;
}
}