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 Source
POJ Monthly--2007.08.05, Huang, Jinsong
|
题意:给一棵二叉树,每个结点在开始有一个苹果,开始给定树的结构,然后有m条询问,如果是字符C那么就改变当前结点的苹果数(1变0,0变1),如果是Q那么就输出以此结点为子树的所有苹果的数目。
思路:首先为什么用树状数组呢,首先,100000不能o(n^2)只能o(n)或o(nlogn)。可以想到线段树和树状数组,当然线段树也可以做,就是麻烦点。树状数组展开是一个完全二叉树(有些空结点是补上的)如图:
结点8存的是结点1~8的和,这跟题目要求恰好一样。通过深搜编号(《算法导论》里面称之为时间戳)编上号以后,题目中的树就可以形成如图:
的结构,这样就可以充分利用树状数组的性质,对于每个结点都有对应的l,r,以它为子树的结点的果实和等于sum(r) - sum(l - 1)。sum(i)为从1到i的果实的和(可以log(n)求得)。代码如下(有对应解释):
#include <cstring>
#include<cstdio>
#define lowbit(i) ((i)&(-i))
using namespace std;
const int N = 100010;
struct nod
{
int v;
int next;
} node[N];
struct
{
int l,r;
} rec[N]; //用于记录每个结点的左右编号
int e;
int head[N];
int c[N];
bool vis[N];
void add(int u,int v)
{
node[e].v = v;
node[e].next = head[u];
head[u] = e;
e++;
}
void dfs(int u,int &num)
{
rec[u].l = num;
for(int i = head[u]; i != -1; i = node[i].next)
{
dfs(node[i].v,num);
num ++;
}
rec[u].r = num;
}
int sum(int n)
{
int ans = 0;
while(n > 0)
{
ans += c[n];
n -= lowbit(n);
}
return ans;
}
void update(int n,int add)
{
while(n < N)
{
c[n] += add;
n += lowbit(n);
}
}
int main()
{
int n, m, u, v;
while(~scanf("%d",&n))
{
memset(head,-1,sizeof(head));
//本题由于vector会超时,所有用手写的静态邻接表存储树结构
memset(node,-1,sizeof(node));
e = 0; //初始化邻接表边的编号
memset(c,0,sizeof(c));
//树状数组赋值0
for(int i = 1; i < n; i ++)
{
scanf("%d%d",&u,&v);
//建树
add(u,v);
vis[i] = 1;//初始化每个编号的苹果
}
vis[n] = 1;
int num = 1; //时间戳初始化
dfs(1,num); //由于数据全是1为根结点所以不需要找根,深搜标号
for(int i = 1; i <= n; i ++) //给树状数组赋初值
update(i,1);
scanf("%d",&m);
char sign[3];
for(int i = 0; i < m; i ++)
{
scanf("%s%d",sign,&u);
if(sign[0] == 'Q')
printf("%d\n",sum(rec[u].r) - sum(rec[u].l - 1));
else if(sign[0] == 'C')
{
if(vis[u])update(rec[u].r,-1);//如果存在苹果,那么本结点减1,更新
else update(rec[u].r,1); //如果不存在苹果,那么本结点加1,更新
vis[u] ^= 1; //异或改变结点的值
}
}
}
return 0;
}