POJ 3321 Apple Tree dfs sequence +fenwick

Source: Internet
Author: User

There is a apple tree full of apples, there are two operations.

1. Ask how many apples are in the subtree with a point root.

2. See if there is an apple at one point, and if there is no apple, then there will be an apple (= =!), or the Apple will be picked off.


Idea: To do a deep search, the first occurrence of each node and the last occurrence of the time in an array, then the point between two points is it and its subtree twice times, and then use a tree array to maintain the interval and on the line.


CODE:

#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define MAX 200010using namespace std;pair<int,int> pos[max];int points,asks;int head[max],total;int next[max << 1], Aim[max << 1];int cnt;bool src[max];int fenwick[max];char c[10];inline void Add (int x,int y); void DFS (int x,int Last ), inline void Fix (int x,int c), inline int getsum (int x), int main () {cin >> points;for (int x,y,i = 1;i < points; + +) i) {scanf ("%d%d", &x,&y); Add (x, y), add (y,x);} (1,-1), memset (src,true,sizeof (SRC)), for (int i = 1;i <= points; ++i) fix (pos[i].first,1), fix (pos[i].second,1); CIN >> asks;for (int x,i = 1;i <= asks; ++i) {scanf ("%s%d", c,&x), if (c[0] = = ' Q ') printf ("%d\n", (Getsum (pos[x). Second)-Getsum (pos[x].first-1)) >> 1); else {if (src[x]) {Fix (pos[x].first,-1); Fix (pos[x].second,-1); src[x] = false;} else {Fix (pos[x].first,1); Fix (pos[x].second,1); src[x] = true;}}} return 0;} inline void Add (int x,int y) {next[++total] =Head[x];aim[total] = y;head[x] = total;} void DFS (int x,int last) {Pos[x].first = ++cnt;for (int i = Head[x];i;i = Next[i]) {if (aim[i] = = last) Continue;dfs (aim[i],x) ;} Pos[x].second = ++cnt;} inline void Fix (int x,int c) {for (; x <= (Points << 1); x + = X&-x) fenwick[x] + = C;} inline int getsum (int x) {int re = 0;for (; x;x-= x&-x) Re + = Fenwick[x];return Re;}


POJ 3321 Apple Tree dfs sequence +fenwick

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.