Poj 2342 anniversary party (tree DP)

Source: Internet
Author: User

Question:

Give some people 1 to n to join a party. Everyone has their own happiness, but there is a leader relationship between these people.

It is required that everyone cannot participate directly with their own leaders to seek the maximum value to satisfy the requirements.

Solution:

Recursive the building of the leadership relationship from the root node (but I am using an array to save a lot of time space. I can use a two-dimensional dynamic array)

DP [I] [1] indicates the maximum value of the selected I node, and DP [I] [0] indicates the maximum value of the unselected I node.

Then the equation is

DP [I] [1] + = All DP [I children] [0)

DP [I] [0] + = max (all DP [I children] [0], all DP [I children] [1]) (I not selected, then his child can choose or not. We choose the maximum value of the two)

# Include <cstdio> # include <iostream> # include <cstring> # include <algorithm> using namespace STD; int DP [6005] [2]; // DP [I] [1] indicates taking I dp [I] [0] indicates not taking int son [6010] [1000]; // son [I] [J] int root [6010], n, a, B; void DFS (int K) // is this the feeling of searching? {Int J, M, s; M = Son [k] [0]; for (j = 1; j <= m; j ++) // m> 0 subnodes will be in the cycle. m = 0 has reached the bottom {S = Son [k] [J]; DFS (s ); DP [k] [1] + = DP [s] [0]; // when K is used, the subnode cannot obtain DP [k] [0] + = max (DP [s] [0], DP [s] [1]); // if K is not used, the subnode can fetch the largest value} int main () {int I, K; while (~ Scanf ("% d", & N) {memset (root, 0, sizeof (Root); memset (son, 0, sizeof (son); memset (DP, 0, sizeof (DP); for (I = 1; I <= N; I ++) scanf ("% d", & DP [I] [1]); while (scanf ("% d", & A, & B) & (A | B )) {son [B] [++ son [B] [0] =; // copy the user's son [B] [0] saves the number of B's sons, saving the code. Root [a] = 1; // locate the root node} for (I = 1; I <= N; I ++) // locate the root node K if (! Root [I]) {k = I; break;} DFS (k); printf ("% d \ n", max (DP [k] [0], DP [k] [1]);} 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.