HDU 3887 Counting Offspring tree Array

Source: Internet
Author: User
/* Question: the relationship between 1-N and edge given on a tree. It is required to obtain the number of subnodes of each vertex that is smaller than the value of the subnode: Tree array. During dfs, sum (x-1) is obtained before entering a node x, then add operation, recursively returning node x and then sum (x-1) the difference between the two sum operations is a number smaller than x. The data volume in this question is large, and the recursion is too deep. Generally, the while + manual stack is used to simulate the recursive process, of course, c ++ can set the stack size so that the stack will not burst */# include <cstdio> # include <iostream> # include <memory. h ># include <queue> # pragma comment (linker, "/STACK: 1024000000,1024000000") using namespace std; const int MAXN = 100009; const int N = 100009; int n, root; struct Edge {int v, next;} edge [2 * MAXN + 10]; int first [MAXN], e, f [MAXN], p [MAXN], pre [MAXN]; inline void addedge (int u, int v) {edge [e]. v = v; edge [e]. next = first [u], first [u] = e ++; edge [e]. v = u; edge [e]. next = first [v], first [v] = e ++;} void init () {memset (first,-1, sizeof (first); memset (f, 0, sizeof (f); e = 0; int u, v; for (int I = 0; I <n-1; I ++) {scanf ("% d", & u, & v); addedge (u, v) ;}} int ar [N]; inline int lowb (int t) {return t & (-t) ;}void add (int I, int v) {for (; I <N; ar [I] + = v, I + = lowb (I);} in T sum (int I) {int s = 0; for (; I> 0; s + = ar [I], I-= lowb (I); return s ;} void dfs (int x, int fa) {pre[ x] = sum (x-1); for (int k = first [x]; k! =-1; k = edge [k]. next) {if (edge [k]. v! = Fa) {p [edge [k]. v] = x; add (edge [k]. v, 1); dfs (edge [k]. v, x) ;}} f [x] = sum (x-1)-pre [x];} void solve () {memset (ar, 0, sizeof (ar )); dfs (root, root); for (int I = 1; I <n; I ++) printf ("% d", f [I]); printf ("% d \ n", f [n]);} int main () {while (scanf ("% d", & n, & root ), n + root) {init (); solve ();} 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.