• 并查集-----好忧伤的并查集


    主要还是看find的join俩个操作,测试数据

    1
    6
    1 2
    4 3
    1 3
    5 6
    6 1
    7 1

    #include <iostream>
    #include <stdio.h>
    #include <memory.h>
    using namespace std;
    
    /**
     * 并查集判断有几个联通子图
     */
    const int maxN = 20;
    int a[maxN];
    int find(int key);
    void join(int s, int e);
    void _init();
    int main()
    {
        freopen("d:\3.txt", "r", stdin);
        int c;
        cin >> c;
        int cc = c;
        while (c--)
        {
            cout << "case:" << cc - c << endl;
            int n;
            int s, e;
            cin >> n;
            int maxNode = -1;
            int node[maxN];
            memset(node, 0, sizeof(node));
            _init();
            for (int i = 0; i < n; i++)
            {
                cin >> s >> e;
                node[s] = 1;
                node[e] = 1;
                maxNode = maxNode > s ? maxNode : s;
                maxNode = maxNode > e ? maxNode : e;
                join(s, e);
            }
            int head[maxN];
            int maxP = -1;
            memset(head, 0, sizeof(head));
            int total = 0;
            for (int i = 0; i <= maxNode; i++)
            {
                if (!node[i])
                    continue;
                int p = find(i);
                maxP = maxP > p ? maxP : p;
                head[p] = 1;
            }
            for (int i = 0; i <= maxP; i++)
            {
                if (head[i] == 0)
                    continue;
                total++;
                cout << "map" << total << " = ";
                for (int j = 0; j <= maxNode; j++)
                {
                    if (!node[i])
                        continue;
                    int p = find(j);
                    if (p == i)
                    {
                        cout << " " << j;
                    }
                }
                cout << endl;
            }
            cout << "total map=" << total << endl << endl;
        }
        return 0;
    }
    
    int find(int key)
    {
        return key == a[key] ? key : a[key] = find(a[key]);
    }
    void join(int s, int e)
    {
        int p1 = find(s);
        int p2 = find(e);
        if (p1 != p2)
        {
            if (p1 >= p2)
                a[p1] = p2;
            else
                a[p2] = p1;
        }
    }
    
    void _init()
    {
        for (int i = 0; i < maxN; i++)
            a[i] = i;
    }

    有错请评论

  • 相关阅读:
    oo第四次博客
    oo第三次博客
    oo第二次博客
    oo第一次博客
    OO第四次博客
    OO第三次博客总结
    第二次博客总结
    oo第一次博客总结
    oo第四次博客作业
    oo第三次博客作业
  • 原文地址:https://www.cnblogs.com/shuiyonglewodezzzzz/p/7110571.html
Copyright © 2020-2023  润新知