Language:Default
Apple Tree
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. 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 |
题目描述
一棵苹果树有若干个分支,每个分叉处有且仅有一个苹果,允许摘掉一个分叉处的苹果,也可能在某一时刻某个没有苹果的分叉处找出一个苹果,要求能够在任意时刻统计任意一个子树上的苹果数目总和。
算法设计
这是一道树状数组题目,如果对树状数组不太熟悉,可以参考树状数组。
苹果树的表示
该苹果树的结构恰好对应了一棵树,但是不是m叉树,所以采用邻接表进行表示。而对于树状数组则直接保存对应编号之间的元素和即可,但是这样树和树状数组没有能够一一对应,所以需要再开始之前做一次DFS遍历,确定以i为根节点的子树的元素区间(注意这里是以DFS序为准,输入编号仅作为查找对应的DFS序),以便于后面的查找。
采摘、生长和查询
采摘和生长对应于树状数组的update,即对应区间的元素从1变为0或者从0变为1,而查询则对应于sum,但是前面说到sum(index)求得的是前index个元素的和,所以对于区间[a,b]进行查询应该是sum(b)-sum(a)。
代码实现
#include <stdio.h>
#include <vector>
#include <cstring>
using namespace std;
void update(int index,int delta);
int sum(int index);
void dfs(int index);
const int MAX = 200000;
int BIT[MAX],Start[MAX],End[MAX],has[MAX];
int lowBit(int x);
vector<vector<int>> graph(MAX);
int N,count = 1;
int main(){
int M;
while(~scanf("%d",&N)){
memset(BIT,0,sizeof(BIT));
memset(has,0,sizeof(has));
memset(Start,0,sizeof(Start));
memset(End,0,sizeof(End));
int a,b;
for(int i = 0;i < MAX;i ++){
graph[i].clear();
}
for(int i = 1;i < N;i ++){
scanf("%d%d",&a,&b);
graph[a].push_back(b);
}
for(int i = 1;i <= N;i ++){
update(i,1);
}
count = 1;
dfs(1);
scanf("%d",&M);
char c[5];
int x;
while(M--){
scanf("%s%d",c,&x);
if(c[0] == 'Q'){//query
printf("%d\n",sum(End[x]) - sum(Start[x] - 1));
}
else{
if(has[x]){//there is a apple
update(Start[x],1);
}
else{
update(Start[x],-1);
}
has[x] = 1-has[x];
}
}
}
return 0;
}
int lowBit(int x){
return x&(-x);
}
void update(int index,int delta){
for(int i = index;i <= N;i += lowBit(i)){
BIT[i] += delta;
}
}
int sum(int index){
int res = 0;
for(int i = index;i > 0;i -= lowBit(i)){
res += BIT[i];
}
return res;
}
void dfs(int index){
Start[index] = count;
for(int i = 0;i < graph[index].size();i ++){
count ++;
dfs(graph[index][i]);
}
End[index] = count;//get the dfs number
}
复杂度分析
构建树状数组时间复杂度为O(n),空间复杂度为O(n),做一次DFS时间复杂度为O(n),查询和更新每次时间复杂度为O(log〖n)〗,假设共有m次,则复杂度为O(mlogn),所以时间复杂度为O(n+m logn),空间复杂度为O(n)。
编程技巧
该题目是一个简单的区间查询问题,但是如果想要使用树状数组进行查询需要连续的编号,题目的输入不一定能够保证这一点,提前进行一次DFS根据DFS序来进行查找可以解决该问题。