1107. Social Clusters (30) 并查集

简介: #include #include #include #include using namespace std;int father[1001];int hobby[1001];int gnum[1001];...
#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
using namespace std;
int father[1001];
int hobby[1001];
int gnum[1001];

int find(int x){
    while (x != father[x]) {
        x = father[x];
    }
    return x;
}

void Union(int a, int b){
    a = find(a);
    b = find(b);
    if(a < b) father[b] = a;
    else father[a] = b;
}

void init(){
    for (int i = 0; i < 1001; i++) {
        father[i] = i;
    }
}

int main(){
    init();
    int n;
    cin >> n;
    
    for (int i = 1; i <= n; i++) {
        int k;
        scanf("%d:", &k);
        for (int j = 0; j < k; j++) {
            int t;
            scanf("%d", &t);
            if(!hobby[t])
                hobby[t] = i;
            Union(i, find(hobby[t]));
        }
    }
    for (int i = 1; i <= n; i++) {
        gnum[find(i)]++;
    }
    int cnt = 0;
    for (int i = 1; i <= n; i++) {
        if(gnum[i] != 0) cnt++;
    }
    sort(gnum, gnum + 1001);
    cout << cnt << endl;
    for (int i = 1000; i > 1000 - cnt; i--) {
        printf("%d%c", gnum[i], i == 1000-cnt+1 ? '\n' : ' ');
    }
    
    return 0;
}


目录
相关文章
|
存储 C++
【PAT甲级 - C++题解】1107 Social Clusters
【PAT甲级 - C++题解】1107 Social Clusters
57 0
PAT (Advanced Level) Practice 1044 Shopping in Mars (前缀和 二分)
PAT (Advanced Level) Practice 1044 Shopping in Mars (前缀和 二分)
96 0
AtCoder Beginner Contest 221 D - Online games(差分 离散化 区间)
AtCoder Beginner Contest 221 D - Online games(差分 离散化 区间)
127 0
HDU-1057,A New Growth Industry(理解题意)
HDU-1057,A New Growth Industry(理解题意)
PAT (Advanced Level) Practice - 1107 Social Clusters(30 分)
PAT (Advanced Level) Practice - 1107 Social Clusters(30 分)
142 0
Data Structures and Algorithms (English) - 6-11 Shortest Path [2](25 分)
Data Structures and Algorithms (English) - 6-11 Shortest Path [2](25 分)
122 0
Data Structures and Algorithms (English) - 6-16 Shortest Path [3](25 分)
Data Structures and Algorithms (English) - 6-16 Shortest Path [3](25 分)
100 0
Data Structures and Algorithms (English) - 6-11 Shortest Path [1](25 分)
Data Structures and Algorithms (English) - 6-11 Shortest Path [1](25 分)
110 0
Data Structures and Algorithms (English) - 6-17 Shortest Path [4](25 分)
Data Structures and Algorithms (English) - 6-17 Shortest Path [4](25 分)
107 0
【1107】Social Clusters (30 分)
【1107】Social Clusters (30 分) 【1107】Social Clusters (30 分)
125 0