题意:有两个操作,问你每次操作后,问你询问点的位置,位置有多少点,以及这个点被移动了多少次。
想法;并查集
#include<iostream>
#include<cstdio>
#include<string.h>
#include<string>
#include<stack>
#include<set>
#include<algorithm>
#include<cmath>
#include<vector>
#include<map>
#define ll __int64
#define lll unsigned long long
#define MAX 1000009
#define eps 1e-8
#define INF 0xfffffff
using namespace std;
struct node
{
int sum;//点的个数
int num;//移动的次数
} p[MAX];
int father[MAX];
void init(int n)
{
for(int i = 1; i<=n; i++)
{
father[i] = i;
p[i].sum = 1;
p[i].num = 0;
}
}
int Find(int x)
{
int temp;
if(father[x]!=x)
{
temp = father[x];
father[x]=Find(father[x]);
p[x].num+=p[temp].num;//每次移动时,我只需要把这个城市的根结点的转移次数+1,等到以后路径压缩时,子结点自己移动的次数加上根结点移动的次数,就是这个结点总共的移动次数,
}
return father[x];
}
void Union(int x,int y)
{
int xx = Find(x);
int yy = Find(y);
if(xx==yy)
return;
else
{
father[xx] = yy;
p[xx].num++;//根节点转移次数+1,要理解
p[yy].sum+=p[xx].sum;//把xx加上父亲节点上
p[xx].sum = 0;
}
}
int main()
{
int t;
int n,m;
char z;
int x,y;
int d = 1;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
init(n);
printf("Case %d:\n",d++);
for(int i = 0; i<m; i++)
{
getchar();
scanf("%c",&z);
if(z=='T')
{
scanf("%d%d",&x,&y);
Union(x,y);
}
else
{
int ss;
scanf("%d",&ss);
int kk = Find(ss);
printf("%d %d %d\n",kk,p[kk].sum,p[ss].num);//这里应该是ss的num而不是ss父亲节点的
}
}
}
return 0;
}