num[i]代表i到根节点的值
这道题一开始竟然以为是线段树= =!后来发现线段树无法进行子区间的维护
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 222222;
int fa[maxn],num[maxn];
int find_father(int u){
if(fa[u] == u)
return fa[u];
else{
int temp = fa[u];
fa[u] = find_father(fa[u]);
num[u] += num[temp];
return fa[u];
}
}
int main(){
int n,m;
while(scanf("%d%d",&n,&m) != EOF){
memset(num,0,sizeof(num));
int cnt = 0;
for(int i = 0; i <= n; i++) fa[i] = i;
for(int i = 0; i < m; i++){
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
x --;
int l = find_father(x),r = find_father(y);
if(l == r){
int e = num[y] - num[x];
if(e != z){
cnt ++;
}
}
else{
fa[r] = l;
num[r] = z + num[x] - num[y];
}
}
printf("%d\n",cnt);
}
return 0;
}
本文通过一个具体的例子详细解析了并查集数据结构的应用场景及其实现方式。文章介绍了一种利用并查集来解决区间更新与查询的问题,并通过具体代码展示了如何通过父节点查找和路径压缩等操作来维护节点间的关系。
767

被折叠的 条评论
为什么被折叠?



