带权并查集-How Many Answers Are Wrong HDU - 3038
题目:
给出一个区间的长度 N,及 M 个子区间和, 形如:x y z, 表示
子区间 [x, y] 的和为 z
如果一个“子区间和”与前面的“子区间和”冲突,即为错误(而且这个“子区间和”将在接下来的判断中被忽略)。
求总错误个数。
Input
有多组数据。
每组数据第一行两个整数N M (1 <= N <= 200000, 1 <= M <= 40000),
接下来每行有 M 对关系 x y z;
注:可以认为 z 为32位整型。
Output
错误个数。
Sample Input
10 5
1 10 100
7 10 28
1 3 32
4 6 41
6 6 1
Sample Output
1
题解:
带权并查集与一般的并查集相比,是将点集中的各点都赋予了一定的权值,这些权值通常是记录的该点到其根结点的代价或者长度。
在压缩路径上与一般并查集有些区别:
//一般并查集
int Find(int root)
{
if(root==pre[root]) return root;
return pre[root]=Find(pre[root]);
}
//带权并查集
int Find(int root)
{
if(root==pre[root]) return root;
int fpre=Find(pre[root]);
sum[root]+=sum[pre[root]];
return pre[root]=fpre;
}
在一般并查集的基础上加了两行代码用来更新结点的权值。
因为在压缩路径之前,sum[root]存储的是root结点与父结点之间的权值,更新之后root直接连接到原先的根结点下,所以要将root结点的值更新,要加上root结点原先的父结点到根结点的权值。
首先fpre指向根结点,
接着更新 当前结点的权值=当前结点的权值+当前结点的父亲结点的权值----sum,
最后返回根结点fpre,同时更新root结点的父结点为原先的根结点----return。
这个过程是个建树的过程。
合并:
当两个有关系的点x、y不在同一点集,将他们的根结点合并,此时:value[px]=-value[x]+value[y]+s,pre[px]=py。
学习了《带权并查集》,写的很详细。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=2e5+5;
const int maxm=4e4+5;
int N,M,l,r,val;
int pre[maxn],sum[maxn];
int Find(int root)
{
if(root==pre[root]) return root;
int fpre=Find(pre[root]);
sum[root]+=sum[pre[root]];
return pre[root]=fpre;
}
int main()
{
while(~scanf("%d%d",&N,&M))
{
memset(sum,0,sizeof(sum));
for(int i=0;i<=N;i++) pre[i]=i;
int ans=0;
for(int i=1;i<=M;i++)
{
scanf("%d%d%d",&l,&r,&val);
l--;//左开右闭,也就是以右端点为根结点
int fl=Find(l),fr=Find(r);
if(fl==fr)
{
if((sum[l]-sum[r])!=val)//属于同一点集但权值冲突
ans++;
}
else //不属于同一点集
{
pre[fl]=fr;//合并点集,l的根结点连接到r的根结点下
sum[fl]=-sum[l]+sum[r]+val;//l的权值要随之改变
}
}
printf("%d\n",ans);
}
return 0;
}