[省赛复习] 带权并查集

来源:互联网 发布:三菱plc编程手册哪里有 编辑:程序博客网 时间:2024/06/04 18:44
P3764树上间距时间限制 : - 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

#include<iostream>#include<cstdio>#define mod 1000using namespace std;int father[50005],dis[50005],n;int _abs(int x){if(x<0) return -x;return x;}int getfather(int x){if(x==father[x]) return x;int _root=getfather(father[x]);dis[x]+=dis[father[x]];father[x]=_root;return _root;}int main(){int x,y,num;scanf("%d",&n);for(int i=1;i<=n;i++) father[i]=i;while(scanf("%d",&num)!=EOF){if(num==1) {scanf("%d%d",&x,&y);father[x]=y;dis[x]=_abs(x-y)%mod;}else {scanf("%d",&x);getfather(x);printf("%d\n",dis[x]);}}}


0 0
原创粉丝点击