-
[KOITP] 동맹의 동맹은 동맹자료구조 및 알고리즘/문제풀이 2017. 1. 12. 07:58
시간 제한 메모리 제한 제출 횟수 정답 횟수 (비율) 정답자 수 2.0 초 512 MB 2639 491 (19%) 382 < Comment >
자료구조를 설명을 듣고 풀었기 때문에 비교적 난이도에 비해 수월하게 풀 수 있었습니다. Union and Find 라는 이름에 맞게 집합을 나누고 이를 그룹별로 파악하는 과정에 적합한 자료구조였습니다. 다만 처음에 시간제한 초과가 난 것은 리턴하는 과정에서 나중에 Find를 수행하더라도 최대한 짧게 수행되도록 find 하고 recursive 하게 되 돌아올때, 각각 원소들의 부모 원소를 최상단 노드로 갱신해주면서 돌아오도록 코딩을 해 주어야 했습니다. 해당 과정이 없을 경우에 호출수가 많이 늘어나 결과적으로 많이 느려짐을 확인했습니다.
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.StringTokenizer; public class FriendsFriend { public static int N = 0; public static int Q = 0; public static int unionFind[] = null; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); N = Integer.parseInt(br.readLine()); Q = Integer.parseInt(br.readLine()); unionFind = new int[N+1]; for (int i = 1 ; i <= N ; i++) { unionFind[i] = i; } StringTokenizer st = null; int isQ = 0; int num1 = 0; int num2 = 0; int root1 = 0; int root2 = 0; for (int q = 0 ; q < Q ; q++) { st = new StringTokenizer(br.readLine()); isQ = Integer.parseInt(st.nextToken()); num1 = Integer.parseInt(st.nextToken()); num2 = Integer.parseInt(st.nextToken()); root1 = findRoot(num1); root2 = findRoot(num2); if (isQ == 0) { // UNION unionFind[root2] = root1; } else { // Question if (root1 == root2) { bw.write("1\n"); } else { bw.write("0\n"); } } } bw.flush(); bw.close(); } public static int findRoot(int a) { if (unionFind[a] == a) { return a; } return unionFind[a] = findRoot(unionFind[a]); } }