uva10608(基础的并查集)

https://vjudge.net/problem/UVA-10608(uva0608 点击打开链接)

思路:并查集,维护一个连通分量。

分析:“靠左”原则,不断地合并区间,维护一颗树的元素个数这个权值(完全是自己写的第一个并查集程序,虽然是简单的套模板,但好在没有看题解了,因为实在是太水了)。

代码:

#include <iostream>
#include <string>
#include <queue>
#include <stack>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <vector>
#include <string.h>
#include <string>
#include <algorithm>
#include <set>
#include <map>
#include <cstdio>
#include <iterator>

using namespace std;

const int maxn = 30000 + 10;
int father[maxn];
int cnt[maxn];
int n,m;

void init(int n)
{
    for(int i = 0; i <= n; i++)
    {
        father[i] = i;
        cnt[i] = 1;
    }
}

int find(int x)
{
    if(x == father[x])
        return x;
    int y = find(father[x]);
    return father[x] = y;
}

void unin(int a,int b)
{
    int fa = find(a);
    int fb = find(b);

    father[fb] = fa;
    cnt[fa] += cnt[fb];
}

int main()
{
    int t,a,b;
    scanf("%d",&t);
    //int father[maxn];
    //int cnt[maxn];
    //int n,m;
    while(t--)
    {
        scanf("%d%d",&n,&m);
        init(n);
        while(m--)
        {
            scanf("%d%d",&a,&b);
           //“靠左”原则
            if(find(a) != find(b))
            {
                unin(a,b);
            }
        }

        int maxn = 0;
        for(int i = 0; i < n; i++)
        {
            if(maxn < cnt[i])
                maxn = cnt[i];
        }

        printf("%d\n",maxn);
    }
}


/*
2
3 2
1 2
2 3
10 12
1 2
3 1
3 4
5 4
3 5
4 6
5 2
2 1
7 1
1 2
9 10
8 9
*/
  • 真正自己思考了才会有收获,不着急,慢慢来,一步一个脚印,加油!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值