Hdu1561 the more, the better

Source: Internet
Author: User

You can build a tree based on the meaning of the question.

To take over child nodes, you must first take over Father's Day points and establish a forest based on this relationship.

The forest becomes a tree by referencing a tree related to all the roots from node 0.

Status definition

OPT [I] [J] indicates the maximum value obtained by selecting J points in the subtree with node I as the root.

Status Transfer

Gem [I] is the input B

OPT [I] [J] = OPT [son1] [J1] + OPT [son2] [J2] + .... + OPT [son-M] [JM] + GEM [I]

D [II] indicates the maximum value obtained by selecting the second node in all the subtree of node I. The array D is calculated using the grouping backpack.

Then OPT [I] [J] = d [J-1] + GEM [I]

Therefore, for OPT [I] [0... m], you can calculate the array D obtained by a grouping backpack.

CodeAs follows:

 # include 
  
    # include 
   
     # include 
    
      # include 
     
       using namespace STD; int N, m; bool flag [220]; int gem [220]; // gem [I] indicates the number of treasures in castle I. Vector 
      
        A [220]; // tree storage. The valid number of the castle is 1, 2, and N. Add a non-existent Castle 0 as the root int OPT [220] [220]. // OPT [I] [J] indicates the maximum value of void DFS (int r) obtained by J nodes in the subtree where I is the root. // In the subtree where R is the root, calculate OPT [r] [0 .... m] {flag [R] = true; For (INT I = 0; I 
        = 0; j --) {for (int K = 0; k <= J; k ++) {d [J] = max (d [J], d [J-K] + OPT [A [r] [I] [k]) ;}} OPT [r] [0] = 0; for (INT I = 1; I <= m; I ++) {OPT [r] [I] = d [I-1] + GEM [R];} int main () {While (scanf ("% d", & N, & M), N | M) {memset (flag, false, sizeof (FLAG); For (INT I = 0; I <= N; I ++) {A [I]. clear () ;}for (INT I = 1; I <= N; I ++) {int A; scanf ("% d", &, & gem [I]); A [A]. push_back (I);} gem [0] = 0; // build M ++; DFS (0); printf ("% d \ n ", OPT [0] [m]);} return 0 ;}
      
     
    
   
  

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.