This repository has been archived by the owner on Sep 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bicolor.java
59 lines (44 loc) · 1.42 KB
/
bicolor.java
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
53
54
55
56
57
58
59
import java.util.*;
public class bicolor {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
while (true) {
int n = stdin.nextInt();
if (n == 0)
break;
int l = stdin.nextInt();
ArrayList<Integer>[] edges = new ArrayList[n];
for (int i = 0; i < edges.length; i++) {
edges[i] = new ArrayList<Integer>();
}
for (int i = 0; i < l; i++) {
int a = stdin.nextInt();
int b = stdin.nextInt();
edges[a].add(b);
}
boolean ans = bicolorable(edges, 0);
System.out.println(ans ? "BICOLORABLE." : "NOT BICOLORABLE.");
}
}
static boolean bicolorable(ArrayList<Integer>[] edges, int s) {
ArrayDeque<Integer> q = new ArrayDeque<Integer>();
int[] color = new int[edges.length];
Arrays.fill(color, -1);
color[0] = 0;
boolean ans = true;
q.offer(0);
while (!q.isEmpty() && ans) {
int u = q.poll();
for (int v : edges[u]) {
if (color[v] == -1) {
color[v] = 1 - color[u];
q.push(v);
} else if (color[v] == color[u]) {
ans = false;
break;
}
}
}
return ans;
}
}