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 for k.
or
“Q x” which means an inquiry for the number of apples in the sub-tree above the for k x, including the apple (if exists) on the for k 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
SourcePOJ Monthly–2007.08.05, Huang, Jinsong
题目描述:
1-n个点,根据输入的信息建树
两个操作:1,修改某个节点的数,如果是1,修改为0; 如果是0,修改为1.
2,查询x子树上的权值和。
算法知识:树状数组来求区间和,dfs序来处理子树问题。
dfs序两个数组为l数组和r数组,分别记录某点进入的时间和出来的时间,中间的差值就是他的子树的个数。
修改的时候是修改 update(l【x】,num),其实是修改s数组的值,l【x】只是定位他是多少时间进入的。s数组可以理解为时间从1-n的数组。
查询就是 getsum ( r[k] ) -getsum( l[k]-1 ) r数组是出的时间,l数组是入的时间,子树的所有子节点进入和出去的时间都存在 在 l , r 数组之间,利用前缀和就能求出权值和。
第x个值的子树权值和就是 l 数组到 r 数组在s数组之前的权值和。
#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>
#include<cstdio>
using namespace std;
const int maxn=1e5+10;
typedef long long ll;
ll s[maxn],sum[maxn],l[maxn],r[maxn];
ll t,tot;
vector<vector<ll> > p(maxn);
int lowbit(int x)
{
return x&(-x);
}
void update(ll x,ll num)
{
while(x<=t)
{
sum[x]+=num;
x+=lowbit(x);
}
}
ll getsum(ll x)
{
ll ans=0;
while(x>0)
{
ans+=sum[x];
x-=lowbit(x);
}
return ans;
}
void dfs(ll x)
{
l[x]=tot;
for(ll i=0;i<p[x].size();i++)
{
tot++;
dfs(p[x][i]);
}
r[x]=tot;
}
int main()
{
scanf("%lld",&t);
for(ll i=1;i<t;i++)
{
ll u,v;
scanf("%lld%lld",&u,&v);
p[u].push_back(v);
}
tot=1;
dfs(1);
for(ll i=1;i<=t;i++)
{
s[i]=1;
update(i,1);
}
ll m;
scanf("%lld",&m);
for(int i=1;i<=m;i++)
{
char str;
ll k;
scanf("%s%lld",&str,&k);
if(str=='Q')
{
printf("%lld\n",getsum(r[k])-getsum(l[k]-1));
}
else
{
if(s[k]==1)
{
s[k]=0;
update(l[k],-1);
}
else
{
s[k]=1;
update(l[k],1);
}
}
}
return 0;
}