pat1107 Social Clusters

题意:n个人,每个人有个兴趣列表,有同样的至少一个兴趣的人在一个圈子里,求有多少个圈子,并把圈子按照人数从大到小输出人数。

思路:并查集维护即可。

代码

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

const int MAX_N = 1010;
int par[MAX_N];
int n, k, x;
map > mp;
map cnt;
vector ans;

void init(int n) {
    for (int i = 1; i <= n; i++) par[i] = i;
}
int find(int x) {
    if (x == par[x]) return x;
    return par[x] = find(par[x]);
}
void uni(int x, int y) {
    x = find(x); y = find(y);
    if (x == y) return ;
    par[x] = y;
}

int main() {
    // freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
    scanf("%d", &n);
    init(n);
    for (int i = 1; i <= n; i++) {
        scanf("%d:", &k);
        for (int j = 0; j < k; j++) {
            scanf("%d", &x);
            mp[x].push_back(i);
        }
    }
    for (auto it = mp.begin(); it != mp.end(); it++) {
        vector& v = it->second;
        if (v.size() == 0) continue;
        int t = v[0];
        for (int i = 1; i < v.size(); i++) {
            uni(t, v[i]);
        }
    }
    for (int i = 1; i <= n; i++) {
        cnt[find(i)]++;
    }
    for (auto i = cnt.begin(); i != cnt.end(); i++) {
        if (i->second > 0)
            ans.push_back(i->second);
    }
    printf("%d\n", ans.size());
    sort(ans.begin(), ans.end(), greater());
    for (int i = 0; i < ans.size(); i++) {
        if (i > 0) printf(" ");
        printf("%d", ans[i]);
    }
    return 0;
}

 

你可能感兴趣的:(pat)