CodeForces - 1013D (并查集)

Innopolis University scientists continue to investigate the periodic table. There are n·m known elements and they form a periodic table: a rectangle with n rows and m columns. Each element can be described by its coordinates (r, c) (1 ≤ r ≤ n, 1 ≤ c ≤ m) in the table.

Recently scientists discovered that for every four different elements in this table that form a rectangle with sides parallel to the sides of the table, if they have samples of three of the four elements, they can produce a sample of the fourth element using nuclear fusion. So if we have elements in positions (r1, c1), (r1, c2), (r2, c1), where r1 ≠ r2 and c1 ≠ c2, then we can produce element (r2, c2).

Samples used in fusion are not wasted and can be used again in future fusions. Newly crafted elements also can be used in future fusions.

Innopolis University scientists already have samples of q elements. They want to obtain samples of all n·m elements. To achieve that, they will purchase some samples from other laboratories and then produce all remaining elements using an arbitrary number of nuclear fusions in some order. Help them to find the minimal number of elements they need to purchase.

。。。

这题的解法为并查集。。。至于原理我讲不清楚,差不多就是把每一行每一列都当作一个元素。。

#include <algorithm>
#include <math.h>
#include <string.h>
#include <vector>
#include <stdio.h>
#include <map>
#include<ctype.h>
using namespace std;

const int MAX = 4e5 + 50;

int par[MAX];
int Rank[MAX];

int Find(int x){
	if(par[x] == x){
		return x;
	} else{
		return par[x] = Find(par[x]);
	}
}

void unit(int x, int y){
	x = Find(x);
	y = Find(y);

	if(Rank[x] < Rank[y]){
		par[x] = y;
	} else{
		par[y] = x;
		if(Rank[x] == Rank[y]){
			Rank[x]++;
		}
	}
}

int main(int argc, char const *argv[]){
	int n, m, q;
	scanf("%d%d%d", &n, &m, &q);

	for(int i = 1; i <= n + m; i++){
		par[i] = i;
	}
	for(int i = 0; i < q; i++){
		int x, y;
		scanf("%d%d", &x, &y);
		unit(x, n + y);
	}

	int ans = 0;
	for(int i = 1; i <= n + m; i++){
		if(par[i] == i){
			ans++;
		}
	}

	printf("%d\n", ans - 1);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43737952/article/details/88985580