diff --git a/solutions/advanced/ac-GameOnTree.mdx b/solutions/advanced/ac-GameOnTree.mdx index 0077393b81..9603884821 100644 --- a/solutions/advanced/ac-GameOnTree.mdx +++ b/solutions/advanced/ac-GameOnTree.mdx @@ -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. @@ -39,6 +41,7 @@ This makes sense because whichever edge that Alice chooses, Bob can choose the o #include #include #include + using namespace std; int main() { @@ -71,4 +74,45 @@ int main() { ``` + + + + +The below solution only works when you submit with PyPy. +Submitting with normal Python will result in MLE. + + + +```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") +``` + +