Explanation
Define as the number of paintings for the subtree of barn with color . Then, our transition for a vertex where iterates over the subtrees of is:
Implementation
Time Complexity:
C++
Code Snippet: C++ Short Template (Click to expand)const int mx = 1e5 + 1, MOD = 1e9 + 7;ll dp[mx][3];vi adj[mx];void dfs(int v, int p = 0) {for (const int &e : adj[v]) {if (e != p) {
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!