Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update BuildingTeams PySol content/3_Silver/Graph_Traversal.mdx #4917

Merged
merged 17 commits into from
Nov 19, 2024
Merged
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 44 additions & 1 deletion content/3_Silver/Graph_Traversal.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1082,6 +1082,49 @@ public class BuildingTeams {
```

</JavaSection>
<PySection>

<Warning>
You have to submit with CPython (not PyPy3) to avoid exceeding the time limit.
</Warning>

```py
import sys

input = sys.stdin.readline
SansPapyrus683 marked this conversation as resolved.
Show resolved Hide resolved

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 +1290,7 @@ for i in range(n):
break

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