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

py sol for Game on Tree #4897

Merged
merged 5 commits into from
Nov 4, 2024
Merged
Changes from all 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
44 changes: 44 additions & 0 deletions solutions/advanced/ac-GameOnTree.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ author: Aakash Gokhale

[Official Editorial (Japanese)](https://atcoder.jp/contests/agc017/editorial)

## Explanation

Since the game in the problem seems similar to Nim, let's try to use Sprague-Grundy numbers.

To solve the problem, for a certain root with subtrees, $s_1, s_2, ..., s_k$, we can try to convert all these subtrees into a stack of some size.
Expand Down Expand Up @@ -39,6 +41,7 @@ This makes sense because whichever edge that Alice chooses, Bob can choose the o
#include <functional>
#include <iostream>
#include <vector>

using namespace std;

int main() {
Expand Down Expand Up @@ -71,4 +74,45 @@ int main() {
```

</CPPSection>
<PySection>

SansPapyrus683 marked this conversation as resolved.
Show resolved Hide resolved
<Warning>

The below solution only works when you submit with PyPy.
Submitting with normal Python will result in MLE.

</Warning>

```py
import sys, pypyjit

# improves performance for deeply recursive functions by allowing PyPy to skip unrolling
pypyjit.set_param("max_unroll_recursion=-1")

sys.setrecursionlimit(10**7)


def dfs(u: int, p: int) -> int:
sg = 0
for v in g[u]:
if v != p:
# Adding 1 because the edge from u to v increases the size of
# each stack by 1
sg ^= dfs(v, u) + 1

return sg


n = int(input())
g = [[] for _ in range(n + 1)]

for _ in range(n - 1):
u, v = map(int, input().split())
g[u].append(v)
g[v].append(u)

print("Alice" if dfs(1, 0) else "Bob")
```

</PySection>
</LanguageSection>
Loading