码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-10-15 17:35:42      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:ret   mes   int   include   clu   name   sizeof   ota   join   

 

主要还是看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;
}

有错请评论

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

标签:ret   mes   int   include   clu   name   sizeof   ota   join   

原文地址:http://www.cnblogs.com/shuiyonglewodezzzzz/p/7110571.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!