Hdu3887 tree array-thinking still needs to be improved ..

Source: Internet
Author: User

Http://acm.hdu.edu.cn/showproblem.php? PID = 1, 3887
Source:

2011 multi-university training contest 5-host by BNU

Given a 10 ^ 5 node tree (represented by 1 -- N), we will tell you the root node and find a number smaller than the number below each node...

Analysis: it is actually the idea of using the reverse order number method... This tree is searched in depth and maintained in a tree array. When each node enters the tree for the first time, the number of nodes that have been scanned is smaller than that of the node is recorded. When the node exits, the number of nodes is recorded again, the subtraction of the two is the result... During the competition, I was always wondering how to remove the excess parts. I could not think of logging into this node... Depressed...
This topic directly explodes the DFS stack, so we need to simulate it...

Post Code first:

# Include <vector> # include <iostream> using namespace STD; const int n = 200010; int N, P, sum [N], ANS [N], STK [N], sn; int pre [N], POS [N], flag [N]; vector <int> A [n]; int query (int I) {int TMP = 0; while (I> 0) {TMP + = sum [I]; I-= I & (-I);} return TMP;} void Update (int I, int V) {While (I <= N) {sum [I] + = V; I + = I & (-I) ;}} void DFS (INT P) // stack simulation... {Int II; Sn = 0; STK [Sn ++] = P; memset (flag, 0, sizeof (FLAG); While (Sn! = 0) {II = STK [sn-1]; If (flag [II] = 0) {pre [II] = query (II); flag [II] = 1 ;} if (A [II]. size ()! = 0) {If (flag [A [II]. back ()] = 0) STK [Sn ++] = A [II]. back (); A [II]. pop_back ();} else {pos [II] = query (II); ans [II] = POS [II]-pre [II]; Update (II, 1 ); sn -- ;}} int main () {int I, X, Y; while (scanf ("% d", & N, & P )! = EOF) {If (n = 0 & P = 0) break; for (I = 0; I <= N; I ++) {sum [I] = 0; ans [I] = 0;} for (I = 1; I <n; I ++) {scanf ("% d ", & X, & Y); A [X]. push_back (y); A [Y]. push_back (x);} DFS (p); for (I = 1; I <n; I ++) printf ("% d", ANS [I]); printf ("% d \ n", ANS [I]);} 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.