Created
September 8, 2017 14:44
-
-
Save developer-sdk/7e812f5c06ce4235a9610ae5db084d12 to your computer and use it in GitHub Desktop.
백준,1717,집합의 표현,유니온 파인드
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.Scanner; | |
| /** | |
| * 백준, 집합의 표현, 1717 | |
| * | |
| * @author User | |
| * | |
| */ | |
| public class Main { | |
| static int N; | |
| static int M; | |
| static int[] parent; | |
| public static void main(String[] args) { | |
| Scanner sc = new Scanner(System.in); | |
| N = sc.nextInt(); | |
| M = sc.nextInt(); | |
| parent = new int[N + 1]; | |
| for (int i = 1; i <= N; i++) | |
| parent[i] = i; | |
| while (M-- > 0) { | |
| int type = sc.nextInt(); | |
| int x = sc.nextInt(); | |
| int y = sc.nextInt(); | |
| if (type == 0) { | |
| union(x, y); | |
| } else if (type == 1) { | |
| System.out.println(find(x) == find(y) ? "YES" : "NO"); | |
| } | |
| } | |
| sc.close(); | |
| } | |
| public static int find(int x) { | |
| if (x == parent[x]) | |
| return x; | |
| int root = find(parent[x]); | |
| parent[x] = root; | |
| return root; | |
| } | |
| public static void union(int x, int y) { | |
| x = find(x); | |
| y = find(y); | |
| parent[y] = x; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment