POJ 3321 Apple Tree

Source: Internet
Author: User

Reference Source: http://www.cnblogs.com/frog112111/p/3269281.html

/**poj 3321 Tree Array + dfs* Test instructions: An apple tree, there are N nodes, each node has or only 1 apples, at the beginning of each node has Apple * gives n-1 node relationship * M Operations: * C x if the X node has an apple, then take off, if not, will grow a A * Q X asks the sum of all the nodes below the X node for the *//*dfs of the first access time and last access time for each node, and the node between begin[x] and End[x] is the subtree of x (End[u) with a tree-like array (getsum)- Getsum (Begin[u]-1) */#include <cstdio> #define LOWBIT (x) x& (-X) #define MAXN 100010int C[MAXN], N;int first[ MAXN]; Record the head node of the adjacency table with the number int BEGIN[MAXN];  Start time of each node int END[MAXN]; End time of each node bool HAS[MAXN]; Record whether the node has an Apple int count;void update (int x, int val) {for (int i = x; i <= n; i + = Lowbit (i)) {C[i] + = val;}} int getsum (int x) {int sum = 0;for (int i = x; i > 0; I-= Lowbit (i)) {sum + = C[i];} return sum;} struct Edge {int V, next;} EDGE[MAXN]; Record edge information void insert (int u, int v) {edge[count].v = V;edge[count].next = First[u];first[u] = count++;} void Dfs (int x) {Begin[x] = + + count;for (int i = first[x]; I! =-1; i = edge[i].next) {dfs (EDGE[I].V);} END[X] = count;} int main () {int u, V, M, Ans;char s[10];scanf ("%d", &n), Count = 0;for (int i = 0; I <= MAXN; i++) {First[i] =-1;} for (int i = 0; i < n-1; i + +) {scanf ("%d%d", &u, &v); Insert (U, v);}  Count = 0;dfs (1);//for (int i = 0; i < n; i++) {//printf ("%d%d%d%d%d\n", First[i], begin[i], end[i], EDGE[I].V, Edge[i].next);//}for (int i = 1; I <= n; i++) {Update (I, 1); has[i] = true;} scanf ("%d", &m), while (m--) {scanf ("%s%d", S, &u), if (s[0] = = ' Q ') {printf ("%d\n", Getsum (End[u])-Getsum (begin[ U]-1));} else {if (Has[u]) {update (Begin[u],-1);} else {update (begin[u], 1);} Has[u] =!has[u];}} return 0;}

  

POJ 3321 Apple Tree

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.