UVa 1197 - The Suspects

題目:有一些人(編號0到n-1),0號攜帶病毒,然後給你一些在一起活動過的組隊,問多少人可能攜帶病毒。

分析:DS,并查集。直接利用并查集統計即可。

說明:confluence弄了一晚上沒裝上╮(╯▽╰)╭。

#include 

//union_set_begin
int sets[30001];
int rank[30001];
int size[30001];

void union_set(int l, int r)
{
	for (int i = l; i <= r; ++ i) {
		rank[i] = 0;
		size[i] = 1;
		sets[i] = i;
	}
}

int union_find(int a)
{
	if (a != sets[a])
		sets[a] = union_find(sets[a]);
	return sets[a];
}

int union_union(int a, int b)
{
	if (rank[a] > rank[b]) {
		sets[b] = a;
		size[a] += size[b];
	}else {
		sets[a] = b;
		size[b] += size[a];
		if (rank[a] == rank[b])
			rank[b] ++;
	}
}
//union_set_end

int main()
{
	int n, m, s, x, y, a, b; 
	while (~scanf("%d%d",&n,&m) && n+m) {
		union_set(0, n-1);
		for (int i = 0; i < m; ++ i) {
			scanf("%d%d",&s, &x);
			for (int j = 1; j < s; ++ j) {
				scanf("%d",&y);
				a = union_find(x);
				b = union_find(y);
				if (a != b)
				union_union(a, b); 
			}
		}
		printf("%d\n",size[union_find(0)]);
	}
	return 0;
}


你可能感兴趣的:(并查集,解题报告)