2524: Ubiquitous Religions: Religion: disjoint-set simply use the included base + disjoint-set

Subject to the effect

There are many religions in the world, you are interested in how many of the students in your school religious beliefs.
Your school students have n (0 <n <= 50000) , you are less likely to ask each person's religious beliefs, because they are less willing to reveal. But when you find two students at the same time, they are willing to tell you whether they are the same religion, the number of religious schools limit you can estimate by many such inquiries. You can think of each student only up to a religious belief.

Entry

Comprising a plurality of sets of input data.
The first line of each data set comprises n and m, 0 <= m <= n (n-1) / 2, followed by m lines each include two numbers i and j, i indicates the student and the student j same religion students are numbered from 1 to n. Input to line n = m = 0 as the end.

Ideas analysis

Disjoint-set basic questions

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

#define MAX 50005
int kind[MAX];

int find(int k) {
	if (k == kind[k])return k;
	else return kind[k] = find(kind[k]);
}

void unite(int x, int y) {
	kind[find(x)] = find(y);
}

int main() {
	int n, m, i = 1;
	while (cin >> n >> m && m + n > 0) {
		int res = 0;
		for (int i = 1; i <= n; i++)kind[i] = i;
		while (m--) {
			int a, b; cin >> a >> b;
			unite(a, b);
		}
		for (int i = 1; i <= n; i++) {
			if (find(i) == i) res++;
		}
		printf("Case %d: %d\n", i++, res);
	}
}

Similar questions

Disjoint-set basis spree
disjoint-set Advanced: maintain two relationships
disjoint-set final body: food chain

Published 186 original articles · won praise 13 · views 9302

Guess you like

Origin blog.csdn.net/csyifanZhang/article/details/105221044