zoukankan      html  css  js  c++  java
  • poj1611

    简单并查集

    View Code
    #include <iostream>
    #include <cstdlib>
    #include <cstdio>
    #include <cstring>
    using namespace std;
    
    #define maxn 30005
    
    int n, m;
    int father[maxn];
    int stk[maxn];
    
    void init()
    {
        for (int i = 0; i < n; i++)
            father[i] = i;
    }
    
    int getanc(int a)
    {
        int top = 0;
        while (father[a] != a)
        {
            stk[top++] = a;
            a = father[a];
        }    
        while (top)
            father[stk[--top]] = a;
        return a;
    }
    
    void merge(int a, int b)
    {
        int x = getanc(a);
        int y = getanc(b);
        father[x] = father[y];
    }
    
    void input()
    {
        int k;
        for (int i = 0; i < m; i++)
        {
            scanf("%d", &k);
            if (k == 0)
                continue;
            int a, b;
            scanf("%d", &a);
            for (int j = 1; j < k; j++)
            {
                scanf("%d", &b);
                merge(a, b);
            }
        }
    }
    
    int work()
    {
        int ret = 0;
        for (int i = 0; i < n; i++)
            if (getanc(i) == getanc(0))
                ret++;
        return ret;
    }
    
    int main()
    {
        //freopen("t.txt", "r", stdin);
        while (scanf("%d%d", &n, &m), n | m)
        {
            init();
            input();
            printf("%d\n", work());
        }
        return 0;
    }
  • 相关阅读:
    51nod——T1267 4个数和为0
    cf220B莫队
    cf220b
    poj1436水平可见线
    poj2528贴海报,,
    poj3468
    hdu1698
    ural1989 单点更新+字符串hash
    cf Queries on a String
    hdu4605
  • 原文地址:https://www.cnblogs.com/rainydays/p/3024495.html
Copyright © 2011-2022 走看看