【例题】【并查集(带权)&题干有诈】NKOJ 3764 树上间距

来源:互联网 发布:太原网络规划研究院 编辑:程序博客网 时间:2024/05/16 01:34

NKOJ 3764 树上间距
时间限制 : - MS 空间限制 : 65536 KB
评测说明 : 时限1000ms
问题描述
有n个节点,初始时每个节点的父亲节点都不存在。你的任务是执行下列两种操作:
1 x y 把节点x的父亲设为y,距离为|x-y| mod 1000 输入保证执行指令前x没有父亲节点
2 x 询问x到它所在这棵树的根节点的距离

输入输入
第一行,两个整数n(5<=n<=50000)
接下来若干行(行数<=100000),每行代表一个操作

输出格式
对于每个2号操作,输出一行,表示计算结果

样例输入
4
2 3
1 3 1
2 3
1 1 2
2 3
1 2 4
2 3

样例输出
0
2
3
5

来源 改编自la3027

思路:
使用并查集存储点的父子关系,一个集合中元素的dis值表示该点到根的距离。
当查询x所在集合根节点时,更新dis[x]。
(有诈:)注意权值只有第一次添加时mod1000,更新时不mod

#include<cstdio>#include<iostream>#include<cmath>#include<cstdlib>using namespace std;const int need=50004;int be[need],dis[need];int d;int getbe(int x){    if(x==be[x]) return x;    else    {        int root=getbe(be[x]);        dis[x]+=dis[be[x]];        return be[x]=root;    }}int main(){    //freopen("a.txt","r",stdin);    int n;    scanf("%d",&n);    for(int i=1;i<=n;i++) be[i]=i;    int k,a,b;    while(scanf("%d",&k)!=EOF)    {        if(k==1)         {            scanf("%d%d",&a,&b);            be[a]=b;            dis[a]=abs(a-b)%1000;        }        else if(k==2)         {            scanf("%d",&a);            getbe(a);//注意要使用dis时,先更新根节点            printf("%d\n",dis[a]);        }    }}
0 0