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 ;}