並查集

## 序言 ##

在算法導論上稱之爲”不相交集合” ,那麼它是一種樹形的數據結構,常用於處理一些不相交集合的合併以及查詢問題。

## 基本操作 ##

1.合併兩個不相交集合(Union(x,y))
原理其實很簡單,先設置一個數組Father[X],表示x的”父親”的編號。那麼,合併兩個不相交集合的方法就是,找到其中一個集合父親的父親(也就是最久遠的祖先),同時呢,將另外一個集合的最久遠的祖先的父親指向它。

## 例子 ##

這裏寫圖片描述
2.判斷兩個元素是否屬於同一集合(Find_Set(X))

本操作可轉換爲兩個元素最久遠祖先是否相同。那麼我們可以採用遞歸實現。

## 優化 ##

1.Find_Set(x)時,路徑壓縮

那麼我們在尋找祖先時,我們一般採用遞歸查找但是當元素很多或是整棵樹變爲一條鏈時,每次Find_Set(X)都是O(n)的複雜度,爲了避免這樣的情況出現,我們需要對路徑進行壓縮,即當我們遞推找到祖先節點後,”回溯”的時候順便將他們的子孫節點都直接指向祖先,這樣以後再次Find_Set(x)時複雜度就變成了O(1)。
如下圖所示:
這裏寫圖片描述

2.Union(x,y)時,按秩合併
即合併的時候將元素少的集合合併到元素多的集合中,這樣合併之後呢樹的高度會相對較小。

## 代碼實現 ##


int father[MAX];  //father[x]表示x的父節點
int rank[MAX];    //rank[x]表示x的秩
 


void Make_Set(int x)
{
    father[x] = x;  //根據實際情況指定的父節點可變化
    rank[x] = 0;    //根據實際情況初始化秩也有所變化
}


//查找x元素所在的集合,回溯時壓縮路徑
int Find_Set(int x)
{
    if (x != father[x])
    {
        father[x] = Find_Set(father[x]);

    }
    return father[x];

}
 //按秩合併x,y 所在的集合
//注意,按秩合併,需要實時第更新秩

void Union(int x, int y)
{
    x = Find_Set(x);
    y = Find_Set(y);

    if (x==y)
    {
        return;
    }
    if (rank[x] > rank[y])
    {
        father[y] = x;
    }
    else
    {
        if (rank[x] == rank[y])
        {
            rank[y]++;
        }
        father[x] = y;
    }
}



## 下面是我從PKU POJ找到的題目 ##

Description

Severe acute respiratory syndrome (SARS), an atypical pneumonia of unknown aetiology, was recognized as a global threat in mid-March 2003. To minimize transmission to others, the best strategy is to separate the suspects from others.
In the Not-Spreading-Your-Sickness University (NSYSU), there are many student groups. Students in the same group intercommunicate with each other frequently, and a student may join several groups. To prevent the possible transmissions of SARS, the NSYSU collects the member lists of all student groups, and makes the following rule in their standard operation procedure (SOP).
Once a member in a group is a suspect, all members in the group are suspects.
However, they find that it is not easy to identify all the suspects when a student is recognized as a suspect. Your job is to write a program which finds all the suspects.
Input

The input file contains several cases. Each test case begins with two integers n and m in a line, where n is the number of students, and m is the number of groups. You may assume that 0 < n <= 30000 and 0 <= m <= 500. Every student is numbered by a unique integer between 0 and n−1, and initially student 0 is recognized as a suspect in all the cases. This line is followed by m member lists of the groups, one line per group. Each line begins with an integer k by itself representing the number of members in the group. Following the number of members, there are k integers representing the students in this group. All the integers in a line are separated by at least one space.
A case with n = 0 and m = 0 indicates the end of the input, and need not be processed.
Output

For each case, output the number of suspects in one line.
Sample Input

100 4
2 1 2
5 10 13 11 12 14
2 0 1
2 99 2
200 2
1 5
5 1 2 3 4 5
1 0
0 0
Sample Output

4
1
1

## 代碼如下 ##
#include<iostream>
 using namespace std;

 int n, m, i, j;
 int father[30005], num[30005];

 void makeSet(int n)
 {
     for(i = 0; i < n; i++)
    {
        father[i] = i; //使用本身做根
        num[i] = 1;
    }
}
int findSet(int x)
{
    if(father[x] != x) //合併後的樹的根是不變的
    {    
        father[x] = findSet(father[x]);
    }
    return father[x]; 
}

void Union(int a, int b)
{
    int x = findSet(a);
    int y = findSet(b);
    if(x == y)
    {
        return;
    }
    if(num[x] <= num[y])
    {
        father[x] = y;
        num[y] += num[x];
    }    else 
    {
        father[y] = x;
        num[x] += num[y];
    }
}

int main()
{
    while(scanf_s("%d %d", &n, &m)!=EOF && n != 0)
    {
        makeSet(n);
        for(i = 0; i < m; i++)
        {
            int count, first, b;
            scanf_s("%d %d",&count, &first);
            for(j = 1; j < count; j++)
            {
                scanf_s("%d",&b);
                Union(first,b);
            }
        }
        printf("%d\n",num[findSet(0)]);
    }
    return 0;
}

詳情請點擊這裏

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章