1118. Birds in Forest 解析

最开始用的HASH的方法,发现有问题。

这里会出现的问题主要是当出现3段的时候,例如:

① 1 2 3

② 4 5 6

③ 3 7 4

的时候Hash会误将这个当成两棵树,而出现问题。

不出现问题的方法估计也有,但是感觉没有直接用并查集方便。

#include <iostream>
#include <vector>
#include <cstring>

#define MAX 10010

using namespace std;

struct Node {
	int bird;
	int father;
};

vector <Node> p;
int n;
vector <int> picture;
int TreeCount[MAX];//用于统计树的数目

void InitSet(int BirdNum) {//初始化并查集
	p.resize(BirdNum);
	for (int i = 0; i < BirdNum; i++) {
		p[i].father = i;
		p[i].bird = 0;
	}
}

void Compress(int top, int x) {//压缩路径
	if (top != p[x].father) {
		Compress(top, p[x].father);
		p[x].father = top;
	}
}


int FindSet(int x) {
	if (x != p[x].father) {
		int top = FindSet(p[x].father);
		Compress(top, x);
	}
	return p[x].father;
}

void Union(int x, int y) {
	int a = FindSet(x);
	int b = FindSet(y);
	p[a].father = b;
}

int main() {
	InitSet(MAX);

	int max = 0;
	int Tree = 0;

	cin >> n;
	for (int i = 0; i < n; i++) {
		int BirdNum;
		int firstBird;
		int Bird;
		cin >> BirdNum;
		for (int j = 0; j < BirdNum; j++) {
			cin >> Bird;

			if (Bird > max)
				max = Bird;

			if (j == 0) {
				firstBird = Bird;
				continue;
			}

			Union(firstBird, Bird);
		}
	}

	memset(TreeCount, 0, sizeof(TreeCount));
	for (int i = 1; i <= max; i++) {
		int father = FindSet(i);
		TreeCount[father]++;
		if (TreeCount[father] == 1) Tree++;
	}
	
	cout << Tree << " " << max << endl;
	int m;
	cin >> m;
	for (int i = 0; i < m; i++) {
		int b1, b2;
		cin >> b1 >> b2;

//		cout << FindSet(b1) << " " << FindSet(b2) << endl;

		if (FindSet(b1) == FindSet(b2))
			cout << "Yes" << endl;
		else
			cout << "No" << endl;
	}

	return 0;
	

}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值