(3635)HDU

题意:有两个操作,问你每次操作后,问你询问点的位置,位置有多少点,以及这个点被移动了多少次。

想法;并查集

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值