When register on a social network, you are always asked to specify your hobbies in order to find some potential friends with the same hobbies. A social cluster is a set of people who have some of their hobbies in common. You are supposed to find all the clusters.
Input Specification:
Each input file contains one test case. For each test case, the first line contains a positive integer N(≤1000)N (≤1000)N(≤1000), the total number of people in a social network. Hence the people are numbered from 1 to NNN. Then NNN lines follow, each gives the hobby list of a person in the format:
KiK_iKi: hih_ihi [1] hih_ihi [2] … hih_ihi [KiK_iKi]
where Ki(>0)K_i(>0)Ki(>0) is the number of hobbies, and hi[j]h_i[j]hi[j] is the index of the jjj-th hobby, which is an integer in [1, 1000].
Output Specification:
For each case, print in one line the total number of clusters in the network. Then in the second line, print the numbers of people in the clusters in non-increasing order. The numbers must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:
8
3: 2 7 10
1: 4
2: 5 3
1: 4
1: 3
1: 4
4: 6 8 1 5
1: 4
Sample Output:
3
4 3 1
Caution:
写法属实有些复杂(不过竟然一遍就AC了hhhh)。
Solution:
// Talk is cheap, show me the code
// Created by Misdirection 2021-08-25 16:48:31
// All rights reserved.
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
int main(){
int n;
scanf("%d", &n);
vector<vector<int>> hobbis(1001), people(n + 1);
for(int i = 0; i < n; ++i){
int num, tmp;
scanf("%d: ", &num);
for(int j = 0; j < num; ++j){
scanf("%d", &tmp);
hobbis[tmp].push_back(i + 1);
people[i + 1].push_back(tmp);
}
}
vector<int> ans;
vector<bool> p(n + 1, false), h(1001, false);
int cnt = 0;
for(int i = 0; i < 1000 & cnt < n; ++i){
if(h[i + 1] == true) continue;
int pos = 0;
while(pos < hobbis[i + 1].size() && p[hobbis[i + 1][pos]] == true) pos++;
if(pos == hobbis[i + 1].size()) continue;
int tmpHobby = i + 1;
int tmpPeople = hobbis[tmpHobby][pos];
ans.push_back(1);
p[tmpPeople] = true;
cnt++;
queue<int> q;
for(int j = 0; j < people[tmpPeople].size(); ++j){
if(h[people[tmpPeople][j]] == true) continue;
q.push(people[tmpPeople][j]);
}
while(!q.empty()){
int thisHobby = q.front();
for(int j = 0; j < hobbis[thisHobby].size(); ++j){
if(p[hobbis[thisHobby][j]] == true) continue;
int thisPeople = hobbis[thisHobby][j];
p[thisPeople] = true;
ans[ans.size() - 1]++;
for(int k = 0; k < people[thisPeople].size(); ++k){
if(h[people[thisPeople][k]] == true) continue;
q.push(people[thisPeople][k]);
}
}
h[thisHobby] = true;
q.pop();
}
}
sort(ans.begin(), ans.end(), greater<int>());
printf("%d\n", (int)ans.size());
for(int i = 0; i < ans.size(); ++i){
if(i == ans.size() - 1) printf("%d\n", ans[i]);
else printf("%d ", ans[i]);
}
return 0;
}