zoukankan      html  css  js  c++  java
  • HDU_1232_并查集

    http://acm.hdu.edu.cn/showproblem.php?pid=1232

    第一道并查集,挺好理解的,初始化,查找根节点,连接,路径压缩。

    #include<iostream>
    #include<cstring>
    #include<cstdio>
    using namespace std;
    int pre[1005],t[1005],n,m,a,b;
    
    int findd(int x)
    {
        int root = x;
        while(pre[root] != root)    root = pre[root];
        int i = x,j;
        while(pre[i] != root)
        {
            j = pre[i];
            pre[i] = root;
            i = j;
        }
        return root;
    
    }
    void join(int a,int b)
    {
        int x = findd(a),y = findd(b);
        if(x != y)  pre[x] = y;
    }
    int main()
    {
        while(scanf("%d",&n) && n)
        {
            scanf("%d",&m);
            for(int i = 1;i <= n;i++)   pre[i] = i;
            while(m--)
            {
                scanf("%d%d",&a,&b);
                join(a,b);
            }
            memset(t,0,sizeof(t));
            for(int i = 1;i <= n;i++)
            {
                t[findd(i)] = 1;
            }
            int ans = 0;
            for(int i = 1;i <= n;i++)
            {
                if(t[i])    ans++;
            }
            printf("%d
    ",ans-1);
        }
        return 0;
    }
  • 相关阅读:
    Manacher算法
    [SCOI2010]生成字符串
    [HNOI2008]GT考试
    矩阵乘法
    关于主席树
    Spring 书籍
    Spark书籍
    TimeMeasure
    Dynamic login
    Image quality evaluation
  • 原文地址:https://www.cnblogs.com/zhurb/p/5914972.html
Copyright © 2011-2022 走看看