uva1329 Corporative Network(并查集:路径压缩)
2016-01-31 16:10
309 查看
题意:初始时有n个点(编号1到n),每个点都没有父节点,然后依次执行下面两条命令:
I u v :把节点u的父亲设置为v,并且设u节点到v的距离为|u-v|%1000,输入保证执行I命令的时候,u没有父节点。
E u:查询u节点到根节点的距离。
输入:首先是T,表示实例个数。每个实例第一行是n(5<=n<=20000),接下有不超过200000行,每行一个指令,以单独的O字母行表示结束。
输出:对于每条E指令,输出查询结果。
思路:并查集+路径压缩维护距离值
I u v :把节点u的父亲设置为v,并且设u节点到v的距离为|u-v|%1000,输入保证执行I命令的时候,u没有父节点。
E u:查询u节点到根节点的距离。
输入:首先是T,表示实例个数。每个实例第一行是n(5<=n<=20000),接下有不超过200000行,每行一个指令,以单独的O字母行表示结束。
输出:对于每条E指令,输出查询结果。
思路:并查集+路径压缩维护距离值
#include <cstdio> #include <queue> #include <cstring> #include <iostream> #include <cstdlib> #include <algorithm> #include <vector> #include <map> #include <string> #include <set> #include <ctime> #include <cmath> #include <cctype> using namespace std; #define maxn 20010 #define LL long long int cas=1,T; int pre[maxn]; int dist[maxn]; int n; void init() { for (int i = 0;i<=n;i++) { pre[i]=i; dist[i]=0; } } int Find(int x) { if (x!=pre[x]) { int f = pre[x]; pre[x]=Find(pre[x]); dist[x]+=dist[f]; return pre[x]; } else return x; // return pre[x]; } int main() { //freopen("in","r",stdin); scanf("%d",&T); while (T--) { scanf("%d",&n); init(); char str[10]; while (scanf("%s",str)) { int a,b; if (str[0] == 'O') break; if (str[0] == 'I') { scanf("%d%d",&a,&b); pre[a]=b; dist[a]=abs(a-b)%1000; } if (str[0] == 'E') { scanf("%d",&a); Find(a); printf("%d\n",dist[a]); } } } //printf("time=%.3lf",(double)clock()/CLOCKS_PER_SEC); return 0; }
相关文章推荐
- Unity3D拖动任意对象GameObject移动到任意地方
- Codeforces 18D Seller Bob
- ubuntu12.04(64位)中以二进制文件(tar.gz)安装mysql5.6.28(64位)
- LeetCode Algorithms #292 <Nim Game>
- Macbook被格式化之后
- C# 读取XML
- java日期计算和比较
- codevs 1421 秋静叶&秋穣子(树上DP+博弈)
- react native使用原生模块
- 杭电 hdu 2089 不要62【数位dp】【入门】
- hdu 3579(中国剩余定理非互质)
- Java 正则 去前后空格 回车
- json_encode 与 json_decode的区别
- ListView给item其中控件添加监听,在Adapter中添加,不难,你可以的。Context帮大忙了
- java_70-73_annotation+Exception
- 第一次向开源项目贡献代码的历程
- 数据结构实践——顺序表应用
- CSS模块化命名
- Liblinear,LibSVM使用整理,总结
- 明明的随机数