题目描述
蓝桥幼儿园的学生是如此的天真无邪,以至于对他们来说,朋友的朋友就是自己的朋友。
小明是蓝桥幼儿园的老师,这天他决定为学生们举办一个交友活动,活动规则如下:
小明会用红绳连接两名学生,被连中的两个学生将成为朋友。
小明想让所有学生都互相成为朋友,但是蓝桥幼儿园的学生实在太多了,他无法用肉眼判断某两个学生是否为朋友。于是他起来了作为编程大师的你,请你帮忙写程序判断某两个学生是否为朋友(默认自己和自己也是朋友)。
输入描述
第 11 行包含两个正整数 N,MN,M,其中 NN 表示蓝桥幼儿园的学生数量,学生的编号分别为 1\sim N1∼N。
之后的第 2 \sim M+12∼M+1 行每行输入三个整数,op , x , yop,x,y:
- 如果 op = 1op=1,表示小明用红绳连接了学生 xx 和学生 yy 。
- 如果 op=2op=2,请你回答小明学生 xx 和 学生 yy 是否为朋友。
1\leq N,M \leq 2\times10^51≤N,M≤2×105,1 \leq x,y\leq N1≤x,y≤N。
输出描述
对于每个 op=2op=2 的输入,如果 xx 和 yy 是朋友,则输出一行 YES
,否则输出一行 NO
。
输入输出样例
示例 1
输入
5 5
2 1 2
1 1 3
2 1 3
1 2 3
2 1 2
输出
NO
YES
YES
运行限制
- 最大运行时间:5s
- 最大运行内存: 256M
思路:模板并查集
AC代码
#include<iostream>
#include<string>
#include<cstring>
#include<map>
#include<set>
#include<cmath>
#include<cstdio>
#include<vector>
#include<stack>
#include<queue>
#include<algorithm>
#define IOS ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define PII pair<int,int>
#define inf 0x3f3f3f3f
#define endl "\n"
typedef long long ll;
using namespace std;
int t,n,m,k;
string s;
const int maxn = 2e5+5;
int fa[maxn];
int find(int x)
{
if(fa[x] == x) return x;
return fa[x] = find(fa[x]);
}
void solve()
{
cin >> n >> m;
for(int i = 1 ; i <= n ; i++) fa[i] = i;
int op,u,v;
while(m--){
cin >> op >> u >> v;
if(op == 1) fa[find(u)] = fa[find(v)];
else{
int fx = find(u);
int fy = find(v);
if(fx == fy) cout << "YES" << endl;
else cout << "NO" << endl;
}
}
}
int main() {
IOS;
solve();
return 0;
}