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