您的位置:首页 > 其它

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指令,输出查询结果。

思路:并查集+路径压缩维护距离值

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: