24/02/01总结

P3367 【模板】并查集

思路:这题考的是并查集而且是标准并查集,并查集有两个作用分别是查找和合并,查找具体效果就是两个结点往上找直到找到头节点,看两个结点的头节点是否相同,若相同则在一棵树上,否则则不在一棵树了,另外的就是并了,就是把一个结点的头节点移到另一颗树的头节点上,因为是标准模板就直接上代码了
ac:

#include "iostream"
using std::cin;
using std::cout;
using std::endl;
int n, m,t1,t2,t3;
struct point {
	int father;
}a[10005];

int find(int t) {
	if (a[t].father == t)return t;
	return a[t].father = find(a[t].father);
}

void Union(int t2, int t3) {
	a[find(t2)].father = find(t3);
}


int main() {
	cin >> n >> m;
	for (int i = 1; i <= n; i++)
	{
		a[i].father = i;
	}
	for (int i = 0; i < m; i++) {
		cin >> t1 >> t2 >> t3;
		if (t1 == 1)
			Union(t2,t3);
		if (t1 == 2)
		{
			if (find(t2) == find(t3))
				cout << 'Y' << endl;	
			else cout << 'N' << endl;
		}
	}
}

P1551 亲戚

思路:这题和上一题一样,就是模板改了一点点而已
ac:

#include "iostream"
using std::cin;
using std::cout;
using std::endl;
int n, m, p,t1,t2;
int a[5005];
int find(int x) {
	if (a[x] == x)return x;
	 return a[x] = find(a[x]);
}

void Union(int t1, int t2) {
	a[find(t1)] = find(t2);
}

int main() {
	cin >> n>>m>>p;
	for (int i = 1; i <= n; i++)
		a[i] = i;
	for (int i = 0; i < m; i++)
	{
		cin >> t1 >> t2;
		Union(t1, t2);
	}
	for (int i = 0; i < p; i++)
	{
		cin >> t1 >> t2;
		if (find(t1) == find(t2))
			cout << "Yes" << endl;
		else cout << "No" << endl;
	}
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值