码迷,mamicode.com
首页 > 其他好文 > 详细

带权并查集模板

时间:2019-07-24 09:46:03      阅读:69      评论:0      收藏:0      [点我收藏+]

标签:har   std   mes   scan   class   using   for   char   while   

#include<cstdio>
#include<iostream>
using namespace std;
int f[30005],d[30005],s[30005];
int find(int x)
{
    if(f[x]==x)return x;
    int tmp=find(f[x]);
    d[x]+=d[f[x]];
    
    return f[x]=tmp;
}
void move(int x,int y)
{
    int sx=find(x);
    int sy=find(y);
    if(sx==sy)return ;
    f[sx]=sy;
    d[sx]=s[sy];
    s[sy]+=s[sx];
}
void search(int x)
{
    find(x);
    printf("%d\n",d[x]);
}
int main()
{
    int q;
    scanf("%d",&q);
    for(int i=1;i<=30000;i++)
    {
        f[i]=i;
        d[i]=0;
        s[i]=1;
    } 
    while(q--)
    {
        char pd;
        cin>>pd;
        if(pd=='M')
        {
            int x,y;
            scanf("%d%d",&x,&y);
            move(x,y);
        }
        else
        if(pd=='C')
        {
            int x;
            scanf("%d",&x);
            search(x);
        }
    }
    return 0;
} 

带权并查集模板

标签:har   std   mes   scan   class   using   for   char   while   

原文地址:https://www.cnblogs.com/ShineEternal/p/11235636.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!