我最开始的思路就是构建连通集,但是在判断两个人是否拥有相同爱好的方法非常笨拙,后来看了网上别人的方法,感觉甚是巧妙,是通过一个hashtable指明已选该课的人的名字,如果你也选了,那么就Union你与该同学。
ac代码
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> father, isRoot;
int cmp1(int a, int b){return a > b;}
int findFather(int x) {
int a = x;
while(x != father[x])
x = father[x];
return x;
}
void Union(int a, int b) {
int faA = findFather(a);
int faB = findFather(b);
if(faA != faB) father[faA] = faB;
}
int main() {
int n, k, t, cnt = 0;
int course[1001] = {0};
scanf("%d", &n);
father.resize(n + 1);
isRoot.resize(n + 1);
for(int i = 1; i <= n; i++)
father[i] = i;
for(int i = 1; i <= n; i++) {
scanf("%d:", &k);
for(int j = 0; j < k; j++) {
scanf("%d", &t);
if(course[t] == 0)
course[t] = i;
Union(i, course[t]);
}
}
for(int i = 1; i <= n; i++)
isRoot[findFather(i)]++;
for(int i = 1; i <= n; i++) {
if(isRoot[i] != 0) cnt++;
}
printf("%d\n", cnt);
sort(isRoot.begin(), isRoot.end(), cmp1);
for(int i = 0; i < cnt; i++) {
printf("%d", isRoot[i]);
if(i != cnt - 1) printf(" ");
}
return 0;
}
我的代码:
#include<iostream>
#include<vector>
#include<algorithm>
#include<map>
using namespace std;
vector<int> v[1001];
int hashTable[1001] = { 0 };
int father[1001];
int findFather(int a) {
int a = x;
while (father[a] != a)
a = father[a];
return a;
}
void join(int a, int b) {
int aa = findFather(a);
int bb = findFather(b);
if (aa == bb)
return;
father[bb] = aa;
}
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
int cnt;
scanf_s("%d:", &cnt);
while (cnt--) {
int temp;
cin >> temp;
v[i].push_back(temp);
}
father[i] = i;
}
for (int i = 1; i < n; i++) {
fill(hashTable, hashTable + 1001, 0);
for (auto c : v[i]) {
hashTable[c] = 1;
}
for (int j = i + 1; j <= n; j++) {
for (auto c : v[j]) {
if (hashTable[c] == 1) {
join(i, j);
break;
}
}
}
}
map<int, int> m1;
for (int i = 1; i <= n; i++) {
if (m1.find(father[i]) == m1.end())
m1[father[i]] = 1;
else
m1[father[i]]++;
}
vector<int> v;
for (auto c : m1) {
v.push_back(c.second);
}
sort(v.begin(), v.end(), greater<int>());
printf("%d\n", v.size());
for (int i = 0; i < v.size(); i++) {
if (i != 0)
printf(" ");
printf("%d", v[i]);
}
printf("\n");
return 0;
}