Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add kattis prob breakingbad in python3 + notes
- Loading branch information
Showing
2 changed files
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
The problem asks to figure out if the given graph is bipartite. A graph colouring solution works, marking nodes the opposite colour to all that they are connected with, and then seeing if you try to colour a node two different colours. If so, the graph is not bipartite. |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
from collections import deque | ||
|
||
def main(): | ||
n = int(input()) | ||
words = [input() for _ in range(n)] | ||
word_to_int = {words[i]:i for i in range(n)} | ||
edges = [[] for _ in range(n)] | ||
#edges = {w:[] for w in words} | ||
|
||
m = int(input()) | ||
for _ in range(m): | ||
a, b = input().split() | ||
i = word_to_int[a] | ||
j = word_to_int[b] | ||
edges[i].append(j) | ||
edges[j].append(i) | ||
|
||
colours = {} | ||
q = deque() | ||
qapp = q.append | ||
for start in range(n): | ||
if start in colours: | ||
continue | ||
qapp((start, True)) | ||
while len(q): | ||
curr, colour = q.pop() | ||
if curr in colours and colours[curr] != colour: | ||
print('impossible') | ||
return | ||
colours[curr] = colour | ||
c = not colour | ||
for o in edges[curr]: | ||
if o in colours: | ||
if colours[o] != c: | ||
print('impossible') | ||
return | ||
else: | ||
qapp((o, c)) | ||
ans = [[], []] | ||
for k in colours: | ||
ans[int(colours[k])].append(words[k]) | ||
print(*ans[0]) | ||
print(*ans[1]) | ||
|
||
|
||
if __name__ == '__main__': | ||
main() |