|
| 1 | +import java.io.*; |
| 2 | +import java.util.*; |
| 3 | + |
| 4 | +/* |
| 5 | + * 이분 그래프 |
| 6 | + */ |
| 7 | + |
| 8 | +public class DH_1707 { |
| 9 | + static ArrayList<Integer> adj[]; |
| 10 | + static boolean[] v, check; |
| 11 | + |
| 12 | + public static void main(String[] args) throws Exception { |
| 13 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 14 | + StringTokenizer st; |
| 15 | + StringBuilder sb = new StringBuilder(); |
| 16 | + |
| 17 | + int t = Integer.parseInt(br.readLine()); |
| 18 | + |
| 19 | + for(int tc = 0; tc < t; tc++) { |
| 20 | + st = new StringTokenizer(br.readLine()); |
| 21 | + |
| 22 | + int V = Integer.parseInt(st.nextToken()), E = Integer.parseInt(st.nextToken()); |
| 23 | + v = new boolean[V + 1]; |
| 24 | + |
| 25 | + adj = new ArrayList[V + 1]; // 인접리스트 |
| 26 | + check = new boolean[V + 1]; // 그래프가 어떻게 나뉘는지에 대한 정보 |
| 27 | + |
| 28 | + for(int i = 0; i < adj.length; i++) adj[i] = new ArrayList<Integer>(); |
| 29 | + |
| 30 | + for(int k = 0; k < E; k++) { |
| 31 | + st = new StringTokenizer(br.readLine()); |
| 32 | + |
| 33 | + int a = Integer.parseInt(st.nextToken()); |
| 34 | + int b = Integer.parseInt(st.nextToken()); |
| 35 | + |
| 36 | + adj[a].add(b); |
| 37 | + adj[b].add(a); |
| 38 | + } |
| 39 | + |
| 40 | + boolean isEven = true; |
| 41 | + |
| 42 | + // 첫 번째 노드부터 마지막 노드까지 BFS를 통해 탐색 |
| 43 | + for(int i = 0; i < V + 1; i++) { |
| 44 | + if(v[i]) continue; |
| 45 | + if(!(isEven = bfs(i))) break; |
| 46 | + } |
| 47 | + |
| 48 | + sb.append(isEven ? "YES" : "NO").append("\n"); |
| 49 | + } |
| 50 | + |
| 51 | + System.out.println(sb); |
| 52 | + } |
| 53 | + |
| 54 | + static boolean bfs(int node) { |
| 55 | + |
| 56 | + boolean isEven = true; |
| 57 | + |
| 58 | + ArrayDeque<Integer> q = new ArrayDeque<Integer>(); |
| 59 | + |
| 60 | + q.add(node); |
| 61 | + v[node] = true; |
| 62 | + |
| 63 | + while(!q.isEmpty()) { |
| 64 | + int current = q.poll(); |
| 65 | + |
| 66 | + for(int next: adj[current]) { |
| 67 | + // 다음 노드가 이미 방문된 상태일 때 |
| 68 | + // 그래프를 이분그래프로 만들기 위해 분리했을 때, 분리되는 결과가 같다면 이분그래프를 만들지 못함 |
| 69 | + if(v[next]) { |
| 70 | + if(check[next] == check[current]) return false; |
| 71 | + continue; |
| 72 | + } |
| 73 | + |
| 74 | + // 다음 노드를 방문하지 않았다면 |
| 75 | + // 그래프를 분리할 때, 현재 노드와 인접한 노드가 같은 그래프에 속하지 않도록 설정해줌 |
| 76 | + v[next] = true; |
| 77 | + check[next] = !check[current]; |
| 78 | + q.add(next); |
| 79 | + } |
| 80 | + } |
| 81 | + return isEven; |
| 82 | + } |
| 83 | +} |
0 commit comments