变形金刚 【并查集】

变形金刚
Description
有一天Stubird买了一台变形金刚,店员说,这台变形金刚和其他那种骗小孩子的不一样 他真的能变形。 这台变形金刚有n个部件,他们能互相连接,组成机器人,当然,也可以变形。 但是有一天,The tesseract 的能量突然消失了,部件散落一地,当然有些部件还连接着。 现在你只有把部件全部连接起来,他就能变回原样,例如,有4个部件,1,2是连接的,3,4也是连接着的 ,你只需要把1和3连接起来(1,4或者2,3或者2,4)他就能变回原样啦。 他现在问你最少需要多少次连接才能把它变回原样?

Input
第一行一个T,表示有T个测试样例 接下来一个n和m(n<=10^5,0<=m<=10^5),n表示部件个数,m表示有多少个部件还连接着 下面m行,每行u,v表示部件u,v是连接着的。(1<=u,v<=n)

Output
求最小的连接次数

Sample Input
2
1 0
5 2
1 2
3 4
Sample Output
0
2

题意:判断有几个不相交集合


#include <stdio.h>
#include <iostream>  
#include <stdio.h>  
#include <math.h>  
#include <algorithm>  
#include <string.h>  

using namespace std;

int p[30005];
int rankk[30005];

int findd(int x)
{
    if (x == p[x])
        return x;
    else return  p[x] = findd(p[x]);
}

void un(int x, int y)
{
    int a, b;
    a = findd(x);
    b = findd(y);
    if (a == b)
        return;
    p[b] = a;
}

int main()
{
    int n, m, t, a, b;
    scanf("%d",&t);
    while (t--)
    {
        scanf("%d%d",&n,&m);
        for (int i = 1; i<=n; i++)
        {
            p[i] = i;
            rankk[i] = 0;
        }

        for (int i = 0; i<m; i++)
        {
            scanf("%d%d",&a,&b);
            un(a,b);
        }

        int ans = 0;
        int f1 = findd(1);
        for (int i = 2; i <= n; i++)
        {
            int fi = findd(i);
            if (fi != f1)
            {
                p[fi] = f1;
                ans++;
            }
        }
        printf("%d\n", ans);
    }
}


#include <stdio.h>
#include <iostream>  
#include <stdio.h>  
#include <math.h>  
#include <algorithm>  
#include <string.h>  

using namespace std;

int p[30005];
int rankk[30005];
int vis[30000];

int findd(int x)
{
    if (x == p[x])
        return x;
    else return  p[x] = findd(p[x]);
}

void un(int x, int y)
{
    int a, b;
    a = findd(x);
    b = findd(y);
    if (a == b)
        return;
    p[b] = a;
}

int main()
{
    int n, m, t, a, b;
    scanf("%d",&t);
    while (t--)
    {
        scanf("%d%d",&n,&m);
        for (int i = 1; i<=n; i++)
        {
            p[i] = i;
            rankk[i] = 0;
            vis[i] = 0;
        }

        for (int i = 0; i<m; i++)
        {
            scanf("%d%d",&a,&b);
            un(a,b);
        }

        int ans = 0;
        for (int i = 1; i <= n; i++)
        {
            int fa = findd(i);
            if (!vis[fa])
            {
                vis[fa] = 1;
                ans++;
            }
        }

        printf("%d\n", ans-1);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值