Educational codeforces round 52f (tree DP, vector)

Source: Internet
Author: User

# Include <bits/stdc ++. h>
Using namespace STD;
Int N, K;
Vector <int> son [1000007];
Int DP [1000007], depth [1000007], ANS [1000007]; // DP [I] indicates the depth of the leaf node closest to I, depth [I] indicates taking I as the root and returning to the number of leaf nodes that I can reach. ans [I] indicates taking I as the root, and the maximum number of leaf nodes can be reached.
Void DFS (INT now ){
If (! Son [now]. Size () {// itself is a leaf node
Depth [now] = 0;
DP [now] = 1;
Return;
}
Int Mn = 1e9, MX = 0;
For (const Int & TMP: Son [now]) {// traverse the child node
DFS (TMP); // continue Deep Search
If (depth [TMP] <k) // if it is less than K, you can go down from now to the leaf node that the child node TMP can reach.
DP [now] + = DP [TMP]; // transmits the leaves that the child can touch to his father.
MX = max (MX, ANS [TMP]-(depth [TMP] <k? DP [TMP]: 0); // depth [TMP] <K, DP [TMP] has been added to DP [now] and removed, MX leaves the largest number of leaf knots that cannot be met once.
Mn = min (Mn, depth [TMP] + 1); // The depth of now is the minimum child depth + 1
}
Depth [now] = Mn; // Mn only places the smallest depth, and none of the subnode's depth is too large, it will only touch the leaf node that meets the meaning of the question once (this time, it will not be able to return to the ancestor node (this DFS parameter)
Ans [now] = DP [now] + mx; // MX can only add one, so it is placed outside the loop.
}
Int main (){
Scanf ("% d", & N, & K );
Int X;
For (INT I = 2; I <= N; I ++ ){
Scanf ("% d", & X );
Son [X]. push_back (I );
}
DFS (1 );
Printf ("% d \ n", ANS [1]);
Return 0;
}

// There is an array to simulate the Linked List's Traversal method.

Educational codeforces round 52f (tree DP, vector)

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.