问题描述
蓝桥幼儿园的学生是如此的天真无邪,以至于对他们来说,朋友的朋友就是自己的朋友。
小明是蓝桥幼儿园的老师,这天他决定为学生们举办一个交友活动,活动规则如下:
小明会用红绳连接两名学生,被连中的两个学生将成为朋友。
小明想让所有学生都互相成为朋友,但是蓝桥幼儿园的学生实在太多了,他无法用肉眼判断某两个学生是否为朋友。于是他起来了作为编程大师的你,请你帮忙写程序判断某两个学生是否为朋友(默认自己和自己也是朋友)。
输入描述
第 11 行包含两个正整数 N,MN,M,其中 NN 表示蓝桥幼儿园的学生数量,学生的编号分别为 1∼N1∼N。
之后的第 2∼M+12∼M+1 行每行输入三个整数,op,x,yop,x,y:
- 如果 op=1op=1,表示小明用红绳连接了学生 xx 和学生 yy 。
- 如果 op=2op=2,请你回答小明学生 xx 和 学生 yy 是否为朋友。
1≤N,M≤2×1051≤N,M≤2×105,1≤x,y≤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
// Problem: 2. 蓝桥幼儿园
// Contest: Lanqiao
// URL:
// https://www.lanqiao.cn/problems/1135/learning/?page=1&first_category_id=1&second_category_id=8&status=1&sort=students_count&asc=0
// Memory Limit: 256 MB
// Time Limit: 5000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
// #define int long long
using u32 = unsigned;
using i64 = long long;
using u64 = unsigned long long;
using PII = pair<int, int>;
const int N = 2e5 + 5;
int p[N];
int find(int x) {
if (x != p[x]) p[x] = find(p[x]);
return p[x];
}
void solve() {
int n, q, op, x, y;
cin >> n >> q;
for (int i = 1; i <= n; i++) p[i] = i;
for (int i = 0; i < q; i++) {
cin >> op >> x >> y;
if (op == 1) {
p[find(x)] = find(y);
} else {
if (find(x) == find(y)) {
cout << "YES\n";
} else
cout << "NO\n";
}
}
}
signed main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
solve();
return 0;
}
/*
* _oo0oo_
* o8888888o
* 88" . "88
* (| -_- |)
* 0\ = /0
* ___/`---'\___
* .' \\| |// '.
* / \\||| : |||// \
* / _||||| -:- |||||- \
* | | \\\ - /// | |
* | \_| ''\---/'' |_/ |
* \ .-\__ '-' ___/-. /
* ___'. .' /--.--\ `. .'___
* ."" '< `.___\_<|>_/___.' >' "".
* | | : `- \`.;`\ _ /`;.`/ - ` : | |
* \ \ `_. \_ __\ /__ _/ .-` / /
* =====`-.____`.___ \_____/___.-`___.-'=====
* `=---='
*
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* 佛祖保佑 永不宕机 永无BUG
*/