Topic Link: Click to open the link
Test instructions
A tree given n points,
0 is the root, the following n-1 line represents the parent node of each point
The last row n number represents the color of each point, 0 is white, and 1 is black.
Divide the tree into several unicom blocks so that each unicom block has and only one black point, asking how many different methods (result mod1e9+7)
Ideas:
Tree DP, each point has 2 states, has been attributed to a black spot and does not belong to a black spot.
#include <cstdio> #include <vector> #include <iostream>using namespace std; #define N 300100#define MoD 1000000007typedef long Long ll;ll dp[n][2]; DP[I][1] means the number of methods that the point of I has been attributed to a black dot//dp[i][0] means the number of methods for which I have not been attributed to a black point int n, col[n];vector<int>g[n];void dfs (int u) {dp[u][1] = Col[u];DP [u][0] = col[u]^1;for (int i = 0; i < g[u].size (); i++) {int v = g[u][i];d fs (v); ll old[2] = {dp[u][0], dp[u][1]} ;DP [U][0] = (old[0]*dp[v][1] +old[0]*dp[v][0])%mod;dp[u][1] = (old[1]*dp[v][1] +old[1]*dp[v][0] +old[0]*dp[v][1])%mod ;}} int main () { int i, J; while (~ scanf ("%d", &n)) {for (i = 0; i < n; i++) g[i].clear (); for (i = 1; i < n; i++) {scanf ("%d", &j); G[j].push_back (i);} for (i = 0; i < n; i++) scanf ("%d", &col[i]);d FS (0);cout<<dp[0][1]<<endl; } return 0;} /*50 1 1 21 0 0 1 1*/
Codeforces 462D Appleman and tree DP