Home BOJ. Bipartite Graph (1707)
Post
Cancel

BOJ. Bipartite Graph (1707)

[Link] https://www.acmicpc.net/problem/1707


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.util.*;
import java.io.*;

public class Main {
	static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	public static void main(String[] args) throws IOException {
		StringBuilder sb = new StringBuilder();
		Queue<Integer> q = new LinkedList<>();
		String[] line;
		int tot = toi(br.readLine());

		loop:
		for(int i = 0; i < tot; i++) {
			q.clear();
			line = br.readLine().split(" ");
			int v = toi(line[0]), e = toi(line[1]);
			int[] group = new int[v];
			ArrayList<LinkedList<Integer>> al = new ArrayList<>();
			for(int j = 0; j < v; j++) al.add(new LinkedList<Integer>());
			for(int j = 0; j < e; j++) {
				line = br.readLine().split(" ");
				al.get(toi(line[0]) - 1).add(toi(line[1]) - 1);
				al.get(toi(line[1]) - 1).add(toi(line[0]) - 1);
			}

			for(int j = 0; j < v; j++) {
				if(group[j] == 0) {
					q.add(j);
					group[j] = 1;
					while(!q.isEmpty()) {
						int bottom = q.poll();
						for(int e1: al.get(bottom)) {
							if(group[e1] != 0) {
								if((group[bottom] & group[e1]) != 0) {
									sb.append("NO\n");
									continue loop;
								}
								continue;
							}
							group[e1] = (group[bottom] & 1) + 1; // group[bottom] == 1 ? 2 : 1
							q.add(e1);
						}
					}
				}
			}
			sb.append("YES\n");
		}
		System.out.print(sb);
	}

	static int toi(String s) { return Integer.parseInt(s); }
}
This post is licensed under CC BY 4.0 by the author.