P3349 ZJOI2016 小星星
Step 1
Naïve DP. We can define \(f[u,j,S]\) to represent the state where we have already solved the problem inside the subtree \(u\) with \(S\), and \(u\) uses id \(j\) (because we need to check up the tree). This is \(\mathcal{O}(n^3 3^n)\).
Step 2
We find that \(S\) is very bulky to transition. We define \(g(S)\) to be the answer using ANY (may use 0 times) elements in \(S\), \(f(T)\) to be the answer using ALL (must use at least once). Then we have: $\(g(S) = \sum_{T \subseteq S}{f(T)}\)$ By subset inversion: $\(f(T) = \sum_{T \subseteq S}{(-1)^{|S| - |T|}g(S)}\)$ And the answer is \(f([1 \dots n])\). Because every element appears once, this forces it to be a permutation. THIS TRICK IS UNIVERSAL.
Now \(g(S)\) computation is light (\(\mathcal{O}(n^3)\) without optimization, \(\mathcal{O}(n^2)\) with DP-on-tree optimization).