并查集简介与实例C++实现

并查集适用问题举例

  • 1、已知,有n个人和m对好友关系
  • 2、如果两个人是直接的或者间接的好友(好友的好友的好友。。。),那么他们属于一个集合,就是一个朋友圈中
  • 3、写出程序,求这n个人中一共有多少个朋友圈

更详细的例子

https://blog.csdn.net/niushuai666/article/details/6662911

并查集核心函数

①初始化函数

使得每个父节点为自身,自成一派

②查找根节点与路径优化

由于根节点的父节点是自身,因此我们通过while来找到根节点。

路径优化是使得所有非根节点的直接父节点是根节点,即只有树的深度为2,先找到根节点,之后把所有根下面的节点的father直接改为根节点。

③两个集合求并

将集合1的根节点的父节点(原来是自身)连到集合2的根节点即可。

实例 PAT 1118 Birds in Forest (25 分)

Some scientists took pictures of thousands of birds in a forest. Assume that all the birds appear in the same picture belong to the same tree. You are supposed to help the scientists to count the maximum number of trees in the forest, and for any pair of birds, tell if they are on the same tree.

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive number  () which is the number of pictures. Then  lines follow, each describes a picture in the format:

   … 

where  is the number of birds in this picture, and ‘s are the indices of birds. It is guaranteed that the birds in all the pictures are numbered continuously from 1 to some number that is no more than .

After the pictures there is a positive number  () which is the number of queries. Then  lines follow, each contains the indices of two birds.

Output Specification:

For each test case, first output in a line the maximum possible number of trees and the number of birds. Then for each query, print in a line Yes if the two birds belong to the same tree, or No if not.

Sample Input:

Sample Output:

作者: CHEN, Yue
单位: 浙江大学
时间限制: 150 ms
内存限制: 64 MB
代码长度限制: 16 KB

代码:

 

留下评论

您的电子邮箱地址不会被公开。 必填项已用*标注