Algorithm 1 union search set

Algorithm 1 union search set

Disjoint-set: i.e., containing 合并集合and 查找集合中的元素tree data structures of the two operations, , , words already covered their functionality. It is often represented by forest in use.

1. Collect and collect ideas

1.1 Algorithm idea

If the elements in the set are regarded as different nodes on the tree, then the problem of judging whether two elements belong to the same set becomes a problem of whether the roots of the tree where they are located are the same root.

1.2 Path compression

There are different branches of the same tree, and there are different levels of leaf nodes (that is, what we call elements) on the branches. In order to check the speed of finding the root node of a leaf node, the parent of all leaf nodes from element x to the root node root is set as the root node when searching. This method of optimization is called path compression .

After path compression optimization, the average complexity can be regarded as the inverse function of Ackerman's function, which can be roughly regarded as a constant in practical applications.

1.3 Problem description

Taking relatives as an example, you may not know that a friend is your relative, he may be the grandson of your great-grandfather's grandfather's son-in-law's cousin's niece.

Through the family map, you can easily determine whether two people are relatives. But when two people’s nearest common ancestors are separated from them by several generations, making the family very large, it becomes very difficult to test the relatives of the two. Write a program to tell whether Marry and Ben are relatives.

Explanation: This is a very classic example of union search. Using the idea of ​​collection, create a collection for each person. At the beginning, the collection element is the person himself, which means that at the beginning, no one is known to be his relatives. In the future, each time a relative is given, the set merge is started. In this way, the collection relationship in the current state is obtained in real time.

And collect

1.4 Main operations

The main operations of combined search are: one initial, two merge, three search, four judgment

  • Initialize and find set (InitUnionFind)
  • Merge two
    elements of two disjoint sets (Union) , find their root nodes respectively, and then point the parent of the root node of one element to the root node of the other element.
  • Find the root of an element (Find)
    find a root element parent--->parent--->parent...... When there are many elements in the way to find the root node of an element, the path compression optimization algorithm is used. Direct the parent of the element to the root node or ancestor.
  • Judge whether two elements belong to the same set (isConnected)
    Judge whether two elements belong to the same set, that is, find their root nodes respectively, and then judge whether the two root nodes are equal.

Two, and find examples

2.1 Smooth project

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 70879 Accepted Submission(s): 37912

Problem Description A
province investigates urban traffic conditions and obtains a statistical table of existing urban roads. The table lists the cities and towns directly connected to each road. The goal of the Provincial Government's "Unblocked Project" is to enable traffic between any two towns in the province (but not necessarily directly connected by roads, as long as they are reachable through roads indirectly). Ask at least how many roads need to be built?

Input
test input contains several test cases. The first line of each test case gives two positive integers, which are the number of towns N (<1000) and the number of roads M; the subsequent M lines correspond to M roads, and each line gives a pair of positive integers, which are The number of two towns directly connected by a road. For simplicity, the towns are numbered from 1 to N.
Note: There can be multiple roads between the two cities, which means that the input of
3 3
1 2
1 2
2 1
is also legal.
When N is 0, the input ends and the use case is not processed.

Output
For each test case, output the minimum number of roads that need to be built in one line.

Sample Input

4 2
1 3
4 3
3 3
1 2
1 3
2 3
5 2
1 2
3 5
999 0
0

Sample Output

1
0
2
998

Hint
Hint

Huge input, scanf is recommended.

Source
Zhejiang University Computer Postgraduate Re-examination Computer Exam-2005

Recommend
JGShining

#include<iostream>
#include<stdio.h>
using namespace std;

int pre[1010];

int unionSearch(int root)
{

    int son,tmp;
    son = root;
    /*查找根节点*/
    while(root!= pre[root])
        root = pre[root];
    /*路径压缩*/
    while(son!= root)
    {
        tmp = pre[son];
        pre[son] = root;
        son = tmp;
    }

    return root; // 返回跟界定啊
}

int main()
{
    int num, road, total,start, end, root1, root2;
    while(scanf("%d", &num) && num && scanf("%d", &road))
    {
        total = num-1;// num-1 个集合(元素);
        for(int i=1; i<=num; i++)
        {
            pre[i] = i; //1.初始化并查集,此时每个元素自己都是根节点
        }

        while(road--)
        {
            scanf("%d%d", &start, &end); //2.不同集合根据路径,开始合并
            root1 = unionSearch(start); //3.查找根节点,路径压缩
            root2 = unionSearch(end);
            if(root1 !=root2)  //4.判断,根节点不一样
            {
                pre[root1] = root2; //选出一个当根节点
                total--; //集合少一个,关系少一个
            }
        }
        cout<<total<<endl; //计算剩余的集合
    }
    return 0;
}

【recommend】

Guess you like

Origin blog.csdn.net/qq_36148847/article/details/83759652