您的位置:首页 > 其它

HDU3635(并查集)

2016-02-03 15:29 211 查看
题目大意:n个龙珠,q个操作。操作T是将第Ath所在的城市里的所有龙珠移向第Bth龙珠所在的城市;操作Q是询问第Ath龙珠所在的城市、所在城市的龙珠总数,以及第Ath龙珠被移动的次数。

#include <cstdio>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <string>
#include <cmath>
using namespace std;
const int maxn = 11111;
struct node
{
int fa, step, sum;
}p[maxn];
int n, m;
void init()
{
for(int i=0; i<=n; i++)
{
p[i].fa = i;
p[i].sum = 1;
p[i].step = 0;
}
}
int find_fa(int x)
{
if(x == p[x].fa)
return x;
int tot = p[x].fa;
p[x].fa = find_fa(p[x].fa);
p[x].step += p[tot].step;
return p[x].fa;
}
void un(int x, int y)
{
int fx = find_fa(x);
int fy = find_fa(y);
if(fx != fy)
{
p[fx].fa = fy;
p[fx].step++;
p[fy].sum += p[fx].sum;
p[fx].sum = 0;
}
}
int main()
{
int T, kase = 0;
scanf("%d", &T);
while(T--)
{
scanf("%d%d", &n, &m);
init();
char op[5];
int from, to, vex;
printf("Case %d:\n", ++kase);
for(int i=0; i<m; i++)
{
scanf("%s", op);
if(op[0] == 'T')
{
scanf("%d%d", &from, &to);
un(from, to);
}
else
{
scanf("%d", &vex);
int ans = find_fa(vex);
printf("%d %d %d\n", ans, p[ans].sum, p[vex].step);
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: