Good friends (and check the collection)

good friend

Title description

There is a strange space called "Digital World", in which many Digimon live in the digital world. Some of them may be good friends, and there are two unwritten rules in the Digimon World:

First, Digimon A and Digimon B are good friends equivalent to Digimon B and Digimon A are good friends

Second, if Digimon A and Digimon C are good friends, and Digimon B and Digimon C are also good friends, then A and B are also good friends

Now give the information of all the good friends of these Digimons. Ask: How many groups can these Digimon be divided into, satisfying that any two Digimon in each group are good friends, and the Digimon between any two groups is not good friend

yangli.png

Input format

The first line of input has two positive integers n (n <= 100) and m (m <= 100), which respectively represent the number of Digimon and the number of groups of good friends. Digimon numbers are 1~n.

Output format

Output an integer, indicating the number of groups that these Digimon can be divided into

Sample input 1

4 2

1 4

2 3

Sample output 1

2

Sample input 2

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

Sample output

3

/*
 *@Author LeeG
 *@Date	2020-10-15 15:40
 *@Content 好朋友(并查集) 
*/
#include <bits/stdc++.h>
using namespace std;
int n, m;
int father[100];

int findFather(int x){		 
	int a = x;
	while(x != father[x]){
		x = father[x];		//先找到根结点 
	}
	//把路径上所有的结点的根结点都改成x
	while(a != father[a]){	//路径压缩,优化查找性能
		int z = a;
		a = father[a];
		father[z] = x;
	} 
	return x;
} 

void Union(int a, int b){
	int fa = findFather(a);
	int fb = findFather(b);
	if(fa != fb){			//判断是否在同一个集合中 
		father[fb] = fa;
	}
}

/*
测试数据:
7 5
1 2
2 3
3 1
1 4
5 6 
*/
int main(){
	cin>>n>>m;
	//1. 初始化father数组,所有结点初始化根结点为本身自己 
	for(int i = 1; i <= n; i++){
		father[i] = i;
	} 
	for(int i = 0; i < m; i++){
		int a, b;
		cin>>a>>b;
		Union(a, b);			//合并a和b所在的集合 
	}
	int ans = 0;
	int s[10001];
	memset(s, 0, sizeof(s));
	for(int i = 1; i <= n; i++){
		int temp = findFather(i);
		if(s[temp] == 0){
			ans++;
			s[temp] = 1;
		}
	}
	cout<<ans;
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_44723496/article/details/109100594