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, , we can try to convert all these subtrees into a stack of some size. Then, by xoring all these stack sizes (like we do in Nim), we can tell whether we win or lose on this tree.
To compute the size of the stack for a subtree, we can recursively solve the problem. For a subtree with node, the size of the stack will be because there are no edges that can be deleted.
If the grundy value of the root is positive, then Alice wins, otherwise if the grundy value of the root is , Bob wins.
Notice that when we get the grundy numbers for each subtree we need to add to all of them before xoring. This is because each stack's size increases by when you consider the edge from the root of to the root of the entire tree.
For example consider the tree:
For the subtrees rooted at and , the grundy values will be . For the tree rooted at , the grundy value will be . This makes sense because whichever edge that Alice chooses, Bob can choose the other one leaving Alice with no edge to delete and she will lose.
Implementation
Time Complexity:
C++
#include <functional>#include <iostream>#include <vector>using namespace std;int main() {int n;cin >> n;vector<vector<int>> g(n + 1);
Python
Warning!
The below solution only works when you submit with PyPy. Submitting with normal Python will result in MLE.
import sys, pypyjit# improves performance for deeply recursive functions by allowing PyPy to skip unrollingpypyjit.set_param("max_unroll_recursion=-1")sys.setrecursionlimit(10**7)def dfs(u: int, p: int) -> int:sg = 0
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!