pat甲级1107

我最开始的思路就是构建连通集,但是在判断两个人是否拥有相同爱好的方法非常笨拙,后来看了网上别人的方法,感觉甚是巧妙,是通过一个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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值