题目链接:POJ 3321
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 30613 | Accepted: 9148 |
Description
There is an apple tree outside of kaka's house. Every autumn, a lot of apples will grow in the tree. Kaka likes apple very much, so he has been carefully nurturing the big apple tree.
The tree has N forks which are connected by branches. Kaka numbers the forks by 1 to N and the root is always numbered by 1. Apples will grow on the forks and two apple won't grow on the same fork. kaka wants to know how many apples are there in a sub-tree, for his study of the produce ability of the apple tree.
The trouble is that a new apple may grow on an empty fork some time and kaka may pick an apple from the tree for his dessert. Can you help kaka?

Input
The first line contains an integer N (N ≤ 100,000) , which is the number of the forks in the tree.
The following N - 1 lines each contain two integers u and v, which means fork u and fork v are connected by a branch.
The next line contains an integer M (M ≤ 100,000).
The following M lines each contain a message which is either
"C x" which means the existence of the apple on fork x has been changed. i.e. if there is an apple on the fork, then Kaka pick it; otherwise a new apple has grown on the empty fork.
or
"Q x" which means an inquiry for the number of apples in the sub-tree above the fork x, including the apple (if exists) on the fork x
Note the tree is full of apples at the beginning
Output
Sample Input
3 1 2 1 3 3 Q 1 C 2 Q 1
Sample Output
3 2
一棵苹果树,在根节点和叶子节点有苹果,每个苹果有标号,初始状态每个节点都有苹果,存在吃苹果和长出新苹果的操作,然后询问一棵子树有多少个苹果。
题目分析:
吃苹果和长出来是单点操作,然后重要的是用dfs序来标记和存进树状数组。
//
// main.cpp
// POJ 3321 Apple Tree
//
// Created by teddywang on 2017/8/23.
// Copyright © 2017年 teddywang. All rights reserved.
//
#include <iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
int N;
const int maxn=1e5+9;
int TreeArray[maxn],lefts[maxn],rights[maxn],fork[maxn];
vector<vector<int>> edge(maxn);
int key;
void dfs(int a)
{
lefts[a]=key;
int len=edge[a].size();
for(int i=0;i<len;i++)
{
key++;
dfs(edge[a][i]);
}
rights[a]=key;
}
int lowbit(int x)
{
return x&(-x);
}
void edit(int a,int num)
{
while(a<=N)
{
TreeArray[a]+=num;
a+=lowbit(a);
}
}
int getsum(int a)
{
int sum=0;
while(a>=1)
{
sum+=TreeArray[a];
a-=lowbit(a);
}
return sum;
}
int main()
{
while(~scanf("%d",&N))
{
memset(lefts,0,sizeof(lefts));
memset(rights,0,sizeof(rights));
memset(fork,0,sizeof(fork));
memset(TreeArray,0,sizeof(TreeArray));
for(int i=0;i<maxn;i++) edge[i].clear();
for(int i=0;i<N-1;i++)
{
int a,b;
scanf("%d%d",&a,&b);
edge[a].push_back(b);
}
key=1;
dfs(1);
for(int i=1;i<=N;i++)
{
fork[i]=1;
edit(i,1);
}
char op[2];
int a;
int m;
scanf("%d",&m);
for(int i=0;i<m;i++)
{
scanf("%s%d",op,&a);
if(op[0]=='Q')
{
printf("%d\n",getsum(rights[a])-getsum(lefts[a]-1));
}
else
{
if(fork[a]) edit(lefts[a],-1);
else edit(lefts[a],1);
fork[a]=!fork[a];
}
}
}
}