方法一:dfs
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector<int> v[1001], ans[1001];
int visited[1001] = { 0 };
int n, cursor = 0;
bool same(int m, int n) {
for (int each1 : v[m]) {
for (int each2 : v[n])
if (each1 == each2) return true;
}
return false;
}
void dfs(int i) {
if (visited[i]) return;
visited[i] = 1;
ans[cursor].emplace_back(i);
//注意这里的j要从0开始遍历!!!
for (int j = 0; j < n; j++) {
if (same(i, j)) dfs(j);
}
}
bool comp2(int x,int y){
return x>y;
}
int main() {
int i, j, k, t;
cin >> n;
char ch;
for (i = 0; i < n; i++) {
cin >> j >> ch;
for (k = 0; k < j; k++) {
cin >> t;
v[i].emplace_back(t);
}
}
for (i = 0; i < n; i++) {
if (!visited[i]) {
dfs(i);
cursor++;
}
}
vector<int> temp;
for(i=0;i<cursor;i++){
temp.emplace_back(ans[i].size());
}
sort(temp.begin(),temp.end(),comp2);
cout << cursor << endl;
cout<<temp[0];
for(i=1;i<cursor;i++) cout<<' '<<temp[i];
return 0;
}
j=i+1,的时候:
j=0的时候:
方法二:并查集
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector<int> v[1001];
int n, book[1001] = { 0 };
bool same(int p, int q) {
for (int each1 : v[p]) {
for (int each2 : v[q])
if (each1 == each2) return true;
}
return false;
}
void init() {
for (int i = 1; i <= n; i++) book[i] = i;
}
int getf(int t) {
if (book[t] == t) {
return t;
}
else {
book[t] = getf(book[t]);
return book[t];
}
}
void merge(int v, int u) {
int t1, t2;
t1 = getf(v);
t2 = getf(u);
if (t1 != t2) book[t2] = book[t1];
return;
}
bool comp(int x, int y) {
return x > y;
}
int main() {
int i, j, k, t;
cin >> n;
char ch;
for (i = 1; i <= n; i++) {
cin >> j >> ch;
for (k = 0; k < j; k++) {
cin >> t;
v[i].emplace_back(t);
}
}
init();
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
if (same(i, j)) {
merge(i, j);
}
}
}
int sum = 0;
vector<int> temp;
for (i = 1; i <= n; i++) {
if (book[i] == i) {
sum = 0;
for (j = 1; j <= n; j++) {
//注意这里对相同爱好群体的判断需要用getf(j)==i而不是book[j]==i!!!
if (getf(j) == i) sum++;
}
temp.emplace_back(sum);
}
}
sort(temp.begin(), temp.end(), comp);
cout << temp.size() << endl;
cout << temp[0];
for (i = 1; i < temp.size(); i++) cout << ' ' << temp[i];
return 0;
}
book[j]==i来统计相同爱好群体时:
用getf(j)==i时:
为什么要用getf(j)==i而不是book[j]==i?因为执行完本题没有明确的判断谁是群体老大的标准,所以导致执行完最后一步还=还有部分成员没有完成路径压缩,所以需要通过geft(j)==i来判断