Apple Tree
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 34141 | Accepted: 10231 |
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
For every inquiry, output the correspond answer per line.
Sample Input
3 1 2 1 3 3 Q 1 C 2 Q 1
Sample Output
3 2
Source
POJ Monthly--2007.08.05, Huang, Jinsong
题意:
一个苹果树,苹果树上有n个树杈,即n个节点,每个节点上有一个苹果,根节点为1,给你 n-1 行,每一行为某两个节点相连,接下来是查询m次,输入一个字符和一个整数num,当输入的字符为“Q”,即询问以num为根节点的子树所有的苹果树,如果输入的字符是“C”,即更改节点num的苹果状态。
题解:
这道题是一道dfs序入门级别的题目, 用dfs序把一颗树换成区间来进行求和,因为换成区间之后是进行单点更新和区间求和,所以可以直接用树状数组来进行做,也可以不用线段树
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
using namespace std;
#define maxn 200005
int a[maxn], b[maxn], c[maxn], d[maxn], n, m;
vector<vector<int> > e(maxn);// 一开始写成 vector<int> e[maxn]; 就会tle
int ans;
int lowbit(int x){
return x&(-x);
}
void add(int x, int q){//单点修改
while(x <= n){
b[x]+=q;
x+=lowbit(x);
}
}
void dfs(int x, int y){
c[x]=++ans;
for(int i = 0; i < e[x].size(); i++){
int z = e[x][i];
if(z == y){
continue;
}
dfs(z,x);
}
d[x]=ans;
}
int getsum(int x){
int ret = 0;
while(x >= 1){
ret += b[x];
x -= lowbit(x);
}
return ret;
}
int main() {
ans = 0;
scanf("%d",&n);
for(int i = 1; i < n; i++){
int u,v;
scanf("%d%d", &u, &v);
e[u].push_back(v);
}
for(int i = 1; i <= n; i++){
a[i] = 1;
add(i,1);
}
dfs(1,0);//dfs序
scanf("%d",&m);
while(m--){
char ss[10];
int num;
scanf("%s", ss);
if(ss[0] == 'Q'){//区间查询
scanf("%d", &num);
printf("%d\n",getsum(d[num]) - getsum(c[num]-1));
}
else {
scanf("%d", &num);
if(a[c[num]]){
a[c[num]] = 0;
add(c[num],-1);
}else {
a[c[num]] = 1;
add(c[num],1);
}
}
}
return 0;
}
。