728x90
https://www.acmicpc.net/problem/1717
(1) Python - UnionFind 구현
import sys
sys.setrecursionlimit(1000000)
input = sys.stdin.readline
N, M = map(int, input().rstrip().split(" "))
parent = [i for i in range(N + 1)]
def find_parent(x):
if parent[x] != x:
parent[x] = find_parent(parent[x])
return parent[x]
def union_parent(a, b):
a = find_parent(a)
b = find_parent(b)
if a < b:
parent[b] = a
else:
parent[a] = b
for _ in range(M):
opr, A, B = map(int, input().rstrip().split())
if opr == 0:
union_parent(A, B)
else:
if find_parent(A) == find_parent(B):
print("YES")
else:
print("NO")
(2) C/C++
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <cstdio>
#include <cstring>
#define INF 987654321;
using namespace std;
int parent[1000001];
int find(int x) { //부모찾기
if (parent[x] == x) return x;
return parent[x] = find(parent[x]);
}
void merge(int a, int b) {
a = find(a);
b = find(b);
if (a == b) return;
parent[b] = a;
}
string isUnion(int a, int b) {
a = find(a);
b = find(b);
if (a == b) return "YES\n";
else return "NO\n";
}
int main() {
int n, m;
scanf("%d %d", &n, &m);
for (int i = 0; i <= n; i++) {
parent[i] = i;
}
while (m--) {
int cmd, a, b;
scanf("%d %d %d", &cmd, &a, &b);
if (cmd == 0) merge(a, b);
else {
cout << isUnion(a, b);
}
}
}
728x90
'Study > Coding Test' 카테고리의 다른 글
[백준] 10026 - 적록색약 Python, C/C++ (0) | 2023.10.11 |
---|---|
[백준] 2470 - 두 용액 Python (0) | 2023.10.11 |
[백준] 1764 - 듣보잡 Python (0) | 2023.10.11 |
[백준] 2563 - 색종이 Python (0) | 2023.10.11 |
[백준] 1339 - 단어 수학 Python (0) | 2023.10.11 |