-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuva_bicoloring.py
124 lines (95 loc) · 2.7 KB
/
uva_bicoloring.py
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# In Obedience to the Truth
# UVa 10004
import collections
class EdgeNode:
def __init__(self):
self.y = None
self.weight = None
def __str__(self):
return(str(self.y))
class Graph:
def __init__(self, nvertices, nedges, directed=False):
self.edges = [None] * nvertices
self.nvertices = nvertices
self.nedges = nedges
self.directed = directed
def outdegree(self, node):
return 0 if self.edges[node] is None else len(self.edges[node])
def show(self):
"""Print the adjacency repr of g."""
for i in range(self.nvertices):
print("{}: ".format(i), end=" ")
if self.edges[i] is None:
print("\n")
else:
print(' '.join(map(str, (ne.y for ne in self.edges[i]))))
def read_graph(g, n, m, directed=False):
for _ in range(m):
x, y = map(int, input().split())
insert_edge(g, x, y, directed)
def insert_edge(g, x, y, directed=False):
e = EdgeNode()
e.y = y
if g.edges[x] is None:
g.edges[x] = [e]
else:
g.edges[x].append(e)
if not directed:
insert_edge(g, y, x, True)
# bfs
def bfs(g, start: int):
"""bfs.
TODO: initialize discovered[], processed[] and parent[]
"""
def process_vertex_early(v: int):
pass
def process_vertex_late(v: int):
pass
def process_edge(x, y):
# pass
global bipartite
if color[x] is color[y] :
bipartite = False
if color[x] is not None:
color[y] = not color[x]
q = collections.deque()
q.append(start)
discovered[start] = True
while q:
v = q.pop()
process_vertex_early(v)
processed[v] = True
for ne in g.edges[v]:
y = ne.y
if (not processed[y]) or g.directed:
process_edge(v, y)
if (not discovered[y]):
q.append(y)
discovered[y] = True
parent[y] = v
process_vertex_late(v)
def two_color(g):
for i in range(g.nvertices):
if not discovered[i]:
color[i] = True
bfs(g, i)
if not bipartite:
return False
return True
if __name__ == "__main__":
while True:
bipartite = True
n = int(input())
if n == 0:
break
m = int (input())
g = Graph(n, m)
read_graph(g, n, m)
discovered = [False] * g.nvertices
processed = [False] * g.nvertices
parent = [-1] * g.nvertices
color = [None] * g.nvertices
if two_color(g):
print('BICOLORABLE.')
else:
print('NOT BICOLORABLE.')