poj-3321 Apple Tree

Source: Internet
Author: User

Test instructions

Given a tree with roots, each node has an apple at the beginning;

There are two actions C x : Make the state of the X node change, the fruit becomes no, there is no;

Q x: Query The total number of fruits on the X-node pips tree;

N,m<=1^5

Exercises

The scope obviously cannot be searched, so we cannot enumerate when summing;

It can be thought of using a tree-like array to maintain and;

So the basic idea is to make the subtree each in an interval, and then the tree-like array is maintained;

This interval is made with DFS, which records the information of the whole subtrees tree in retrospect;

Specific or look at the code bar, deep search of the process and the like;

Card vector


Code:

#include <stdio.h> #include <string.h> #include <algorithm> #define N 100001using namespace Std;int Next[n<<1],head[n],to[n<<1];int tree[n],data[n],en[n],tot,cnt;bool A[N];char str[100];void Add (int x, int y) {to[++cnt]=y;next[cnt]=head[x];head[x]=cnt;} int lowbit (int k) {return k& (-K);} void Update (int k,int val) {while (k<=n) {tree[k]+=val;k+=lowbit (k);}} int query (int k) {int ret=0;while (k) {ret+=tree[k];k-=lowbit (k);} return ret;} void Dfs (int x,int pre) {int i,y;update (x,1); A[x]=1;data[x]=++tot;for (I=head[x];i;i=next[i]) {if ((Y=to[i])!=pre) {Dfs (y,x);}} En[x]=tot;} int main () {int n,m,i,j,k,x,y;scanf ("%d", &n), for (i=1;i<n;i++) {scanf ("%d%d", &x,&y), add (x, y), add (y,x );} DFS (1,0); scanf ("%d\n", &m), for (i=1;i<=m;i++) {scanf ("%s", str), if (str[0]== ' C ') {scanf ("%d", &x); if (A[x]) A[x]=0,update (data[x],-1); Elsea[x]=1,update (Data[x], 1);} ELSE{SCANF ("%d", &x);p rintf ("%d\n", Query (En[x])-query (data[x]-1));}} 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.