Codeforces 462D Appleman and Tree dp
Question link: Click the open link
Question:
Tree with n points given,
0 is the root, and the n-1 lines below indicate the parent node of each vertex.
The n number in the last line indicates the color of each vertex. 0 indicates white and 1 indicates black.
Divide the tree into several connected blocks so that each connected block has only one black spot and ask how many classification methods are available (result mod1e9 + 7)
Ideas:
Tree-like dp. Each vertex has two States, which are already attributed to a certain black point and not to a certain Black Point.
# Include
# Include
# Include
Using namespace std; # define N 300100 # define mod 1000000007 typedef long ll; ll dp [N] [2]; // dp [I] [1] indicates the number of methods that point I has belonged to a black spot. // dp [I] [0] indicates the number of methods int that point I has never belonged to a black spot. n, col [N]; vector
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]; dfs (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]); dfs (0 ); cout <