并查集CF445B

本文介绍如何使用并查集解决数值关系问题,通过输入数值和关系,找到哪些数值可以形成关系网络,并计算最终结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题 http://codeforces.com/problemset/problem/445/B
//题目大意,输入两个数,n和m,n代表有n个数,m代表有m种关系,接下来输入m行。依次将这些数字放入到一个容器里,
//如果加入的数和前面的数字有关系。则乘2.
//思路,一道并查集。找出哪些数字的父亲节点不是他自己

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <ctype.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
#define N 55
int father[N];
int n,m;

int find(int x){
	int r=x;
	while(father[r] != r){
		r = father[r];
	}
	int i = x;
	int k;
	while(i != r){
		k = father[i];
		father[i] = r;
		i = k;
	}

	return r;
}

int main(){
	int i;
	int a,b;
	__int64 ans;//第一次做cf木有经验。开始的时候是用int的,wa掉了。。。。
	int sum;

	while(~scanf("%d%d",&n,&m)){
		memset(father,0,sizeof(father));
		for(i=1;i<=n;i++)
			father[i] = i;
		sum = 0;
		ans = 1;
		for(i=1;i<=m;i++){
			scanf("%d%d",&a,&b);
			int f1 = find(father[a]);
			int f2 = find(father[b]);
			if(f1 != f2){
				father[f1] = f2;
			}
		}
		for(i=1;i<=n;i++){
			if(father[i] != i)
				sum++;
		}
		for(i=1;i<=sum;i++)
			ans = ans*2;
		printf("%I64d\n",ans);
	}

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值