Skip to content

Commit

Permalink
Merge pull request #4917 from CryoJS/patch4
Browse files Browse the repository at this point in the history
Update BuildingTeams PySol content/3_Silver/Graph_Traversal.mdx
  • Loading branch information
SansPapyrus683 authored Nov 19, 2024
2 parents 09f76b5 + faa6477 commit 13e69c7
Showing 1 changed file with 46 additions and 1 deletion.
47 changes: 46 additions & 1 deletion content/3_Silver/Graph_Traversal.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1082,6 +1082,51 @@ public class BuildingTeams {
```
</JavaSection>
<PySection>
<Warning>
You have to submit with CPython (not PyPy3) to avoid TLE.
</Warning>
```py
import sys

input = sys.stdin.readline

sys.setrecursionlimit(int(1e9)) # disable recursion limit

n, m = map(int, input().strip().split())
adj = [[] for _ in range(n)]
team = [0] * n # 0: not assigned yet, 1: team 1, 2: team 2

for _ in range(m):
a, b = map(int, map(int, input().strip().split()))
adj[a - 1].append(b - 1)
adj[b - 1].append(a - 1)


def dfs(node: int):
for next_node in adj[node]:
if team[next_node]:
if team[next_node] == team[node]:
print("IMPOSSIBLE")
exit()
else:
team[next_node] = 2 if team[node] == 1 else 1
dfs(next_node)


for node in range(n):
if not team[node]:
team[node] = 1
dfs(node)

print(*team)
```
</PySection>
</LanguageSection>
### BFS Solution
Expand Down Expand Up @@ -1247,7 +1292,7 @@ for i in range(n):
break

if valid:
print(" ".join(str(i) for i in assigned))
print(*assigned)
else:
print("IMPOSSIBLE")
```
Expand Down

0 comments on commit 13e69c7

Please sign in to comment.