Codeforces 462D Appleman and Tree dp

Source: Internet
Author: User

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 <
     
      


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.