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;
}

 

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值