【PAT A1107】Social Cluster

在這裏插入圖片描述
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

思路
從輸入樣例的第一個人開始,活動爲2,7,10的人都可以藉由1做朋友,也就是說,我們可以把2,7,10作爲一個集合,不妨把每一行的第一個活動的根作爲根,把後面的活動的根全都併到這個根上,並且每輸入一行就把這個根的人數加一即可。(這題de了我好久bug,還是菜)

#include <cstdio>
#include <algorithm>
using namespace std;

bool cmp(int a, int b){
	return a > b;
}

int main(){
	int father[1010];//記錄活動的集合關係
	int cnt[1010] = {0};//cnt[i]用於記錄活動i的人數(非根爲0)
	for(int i = 0; i < 1010; i++)
		father[i] = i;

	int num;
	scanf("%d", &num);
	for(int i = 0; i < num; i++){
		int numHobby, root;
		scanf("%d:", &numHobby);
		for(int j = 0; j < numHobby; j++){
			int hobby;
			scanf("%d", &hobby);
			if(j == 0){
				while(father[hobby] != hobby)
					hobby = father[hobby];
				root = hobby;
				cnt[root]++;
			}
			else{
				while(father[hobby] != hobby)
					hobby = father[hobby];
				if(hobby != root){
					cnt[root] += cnt[hobby];
					cnt[hobby] = 0;
					father[hobby] = root;
				}
			}
		}
	}
	sort(cnt, cnt + 1010, cmp);
	int total = 0;
	for(int i = 0; i < 1010; i++){
		if(cnt[i] != 0)
			total++;
		else
			break;
	}	
	printf("%d\n", total);
	for(int i = 0; i < total; i++){
		printf("%d", cnt[i]);
		if(i < total - 1)
			printf(" ");
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章