我的数据结构与算法题目集代码仓:https://github.com/617076674/Data-structure-and-algorithm-topic-set
原题链接:https://pintia.cn/problem-sets/15/problems/840
题目描述:
知识点:深度优先遍历、并查集
思路一:深度优先遍历
用set<int> club[]保存每个俱乐部对应的学生信息,用set<int> student[]保存每个学生对应的俱乐部信息。
对M个俱乐部进行深度优先遍历,用bool visited[]数组标记某俱乐部是否已被访问过。
遍历M个俱乐部,如果当前俱乐部未被访问过,则清空set<int> cluster,代表即将加入一个新的学生编号集群,深度优先遍历当前俱乐部编号。
深度优先遍历函数如下:
在visited数组中标记当前节点nowVisit已被访问过,将当前俱乐部的学生加入到cluster中,并遍历当前俱乐部的所有学生,所有学生又遍历其对应的所有俱乐部,一旦发现未访问的俱乐部,即递归调用函数,深度优先遍历该俱乐部。
时间复杂度是O(M * N)。空间复杂度是O(30001)。
C++代码:
#include<iostream>
#include<set>
using namespace std;
int N, M;
set<int> club[1000], student[30001], cluster;
bool visited[1000];
int result = 0;
void dfs(int nowVisit);
int main(){
scanf("%d %d", &N, &M);
for(int i = 0; i < M; i++){
int Mi, num;
scanf("%d", &Mi);
for(int j = 0; j < Mi; j++){
scanf("%d", &num);
student[num].insert(i);
club[i].insert(num);
}
}
fill(visited, visited + M, false);
for(int i = 0; i < M; i++){
if(!visited[i]){
cluster.clear();
dfs(i);
if(cluster.size() > result){
result = cluster.size();
}
}
}
printf("%d\n", result);
return 0;
}
void dfs(int nowVisit){
visited[nowVisit] = true;
for(set<int>::iterator it = club[nowVisit].begin(); it != club[nowVisit].end(); it++){
cluster.insert(*it);
}
for(set<int>::iterator it1 = club[nowVisit].begin(); it1 != club[nowVisit].end(); it1++){
for(set<int>::iterator it2 = student[*it1].begin(); it2 != student[*it1].end(); it2++){
if(!visited[*it2]){
dfs(*it2);
}
}
}
}
C++解题报告:
思路二:并查集
每个俱乐部的学生拥有相同的父亲节点。
时间复杂度和空间复杂度均是O(N)。
C++代码:
#include<iostream>
#include<set>
using namespace std;
int N, M, father[30001];
int findFather(int x);
void unionTwo(int a, int b);
int main(){
scanf("%d %d", &N, &M);
for(int i = 1; i <= N; i++){ //并查集的初始化
father[i] = i;
}
for(int i = 0; i < M; i++){
int Mi;
scanf("%d", &Mi);
int students[Mi];
for(int j = 0; j < Mi; j++){
scanf("%d", &students[j]);
}
for(int j = 1; j < Mi; j++){
unionTwo(students[j - 1], students[j]);
}
}
int count[N + 1];
fill(count + 1, count + N + 1, 0);
for(int i = 1; i <= N; i++){
count[findFather(i)]++;
}
int result = 0;
for(int i = 1; i <= N; i++){
if(count[i] > result){
result = count[i];
}
}
printf("%d\n", result);
return 0;
}
int findFather(int x){
int a = x;
while(x != father[x]){
x = father[x];
}
while(a != father[a]){
int z = a;
a = father[a];
father[z] = x;
}
return x;
}
void unionTwo(int a, int b){
int a_father = findFather(a);
int b_father = findFather(b);
if(a_father != b_father){
father[a_father] = b_father;
}
}
C++解题报告: