1107. Social Clusters (30)
并查集,路径压缩忘记怎么写,然后他是从1开始的。。。我一开始从0开始,不知道为什么错了,找了很久。。
#include<iostream> #include<string> #include<map> #include<vector> #include<algorithm> #include<queue> #include<set> #include<stack> using namespace std; int hobby[1001]; int father[1001]; int num; int findf(int x) { int a = x; while (father[x] != x) { x = father[x]; } while (a != father[a]) { int z = a; a = father[a]; father[z] = x; } return x; } void Union(int a, int b) { int fa = findf(a); int fb = findf(b); if (fa != fb) { father[fa] = fb; } } int main() { fill(hobby, hobby + 1001, 0); cin >> num; for (int i = 1; i <= num; i++) { father[i] = i; } for (int i = 1; i <= num; i++) { int n; scanf_s("%d: ", &n); for (int j = 1; j <= n; j++) { int temp; cin >> temp; if (hobby[temp] == 0) { hobby[temp] = i; } Union(i, findf(hobby[temp])); } } int count[1001]; fill(count, count + 1001, 0); for (int i = 1; i <= num; i++) { count[findf(i)]++; } sort(count, count + 1001); reverse(count, count + 1001); int k=0; while (count[k] != 0) { k++; } cout << k<<endl; for (int i = 0; i < k; i++) { if (i == 0) cout << count[i]; else cout << ' ' << count[i]; } system("pause"); }
浙公网安备 33010602011771号