Table of Contents

ExplanationImplementation

Official Editorial (Java)

Explanation

Define dp[i][j]\texttt{dp}[i][j] as the number of paintings for the subtree of barn ii with color jj. Then, our transition for a vertex vv where ee iterates over the subtrees of vv is:

dp[v][c]=eccdp[e][c]\texttt{dp}[v][c] = \prod_e \sum_{c' \neq c} \texttt{dp}[e][c']

Implementation

Time Complexity: O(N)\mathcal{O}(N)

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!