PAT1107 Social Clusters (30分)

In this question, I use tree structure to store set in array which have two operations: union and findroot.

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

using namespace std;

const int MAXN = 1100;
int S[MAXN];
int H[MAXN];
int N;

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

void Union(int *S, int a, int b)
{
	if (S[a] < S[b]) {
		S[a] += S[b];
		S[b] = a;
	}
	else
	{
		S[b] += S[a];
		S[a] = b;
	}
}

int Find(int *S, int a)
{
	if (S[a] < 0) return a;
	else return S[a] = Find(S, S[a]);
}

int main() {

	memset(S, -1, sizeof(S));
	memset(H, 0, sizeof(H));
	cin >> N;
	int K, hid;
    char ch;
	for (int i = 1; i <= N; i++)
	{
		cin >> K >> ch;
		for (int j = 0; j < K; j++)
		{
			cin >> hid;
			if (H[hid] == 0) H[hid] = i;
			else {
				int r1 = Find(S, H[hid]);
                int r2 = Find(S,i);
				if(r1!=r2)Union(S, r1, r2);
			}
		}

	}
	
	vector<int> num;
	for (int i = 1; i <= N; i++)
	{
		if (S[i] < 0) {
			num.push_back(abs(S[i]));
		}
	}

	sort(num.begin(), num.end(), cmp);
	cout << num.size() << endl;
	bool first = true;
	for (int i=0;i<num.size();i++)
	{
		if (first) { cout << num[i]; first = false; }
		else cout <<' '<< num[i];
	}
	cout << endl;

	return 0;

}

.

你可能感兴趣的:(算法)