Poj3321apple Tree "DFS-like array"

Source: Internet
Author: User

The main topic: a tree (not necessarily a two-fork tree!!) ), the tree has an apple on its node and requires the following:

1. Specify a node, if the node originally has an apple to take it, if there is no Apple then fill in an apple

2. Ask a node and its subtree how many apples there are

Idea: Dfs this tree, recorded the first time to reach the node and the time to walk away, so a node becomes an interval, the left and right endpoints are the beginning of the time to traverse and end the time of the traversal, the interval is sandwiched between the node's subtree!! Interval endpoint record There is no apple, so the problem becomes to ask an interval and the problem, and the addition and subtraction of the apple is the interval endpoint +1 and -1 can be used to solve the tree array of the two operations

#include <cstdio>

#include <string.h>

#include <iostream>

#define MAXN 200009

using namespace Std;

INTNOW=0,TREE[MAXN]={0},N,NEXT[MAXN]={0},ROOT[MAXN]={0},EDGE[MAXN]={0},START[MAXN]={0},END[MAXN]={0};

int lowbit (int x) {return x & (-X);}

void Add (int x,int c)

{

while (X<=2*n)

{

Tree[x]+=c;

X+=lowbit (x);

}

}

int get (int x)

{

int sum=0;

for (int i=x;i>=1;i=i-lowbit (i)) sum+=tree[i];

return sum;

}

void Addedge (int x,int y)

{

NEXT[++NOW]=ROOT[X];

Edge[now]=y;

Root[x]=now;

}

void Dfs (int j)

{

Start[j]=++now;

for (int i=root[j];i!=0;i=next[i]) DFS (edge[i]);

End[j]=++now;

}

int main ()

{

int X,y,m,ope,flag;

Char ch[2];

scanf ("%d", &n);

for (int i=1;i<=n-1;i++)

{

scanf ("%d%d", &x,&y);

Addedge (x, y);

}

now=0;

DFS (1);

for (int i=1;i<=2*n;i++)

Add (i,1);

scanf ("%d", &m);

for (int i=1;i<=m;i++)

{

scanf ("%s%d", Ch,&ope);

if (ch[0]== ' Q ')

{

printf ("%d\n", (Get (End[ope])-get (start[ope]-1)) >>1);

}

Else

{

Flag=get (End[ope])-get (end[ope]-1);

if (flag==1) Flag=-1;else flag=1;

Add (Start[ope],flag);

Add (End[ope],flag);

}

}

return 0;

}

Debug result: 1 times AC

Poj3321apple Tree "DFS-like array"

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.