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
|
提示
示例程序
Source Code
Problem: 3321 Code Length: 1608B
Memory: 6608K Time: 704MS
Language: GCC Result: Accepted
#include <stdio.h>
#include <string.h>
struct
{
int v,next;
}w[100001];
int c[100001],h[100001],start[100001],end[100001],numw,vis[100001],deep,apple[100001];
int lowbit(int x)
{
return x&(-x);
}
void insert(int u,int v)
{
w[numw].v=v;
w[numw].next=h[u];
h[u]=numw;
numw++;
}
void dfs(int t)
{
int i;
deep++;
start[t]=deep;
for(i=h[t];i!=-1;i=w[i].next)
{
if(vis[w[i].v]==0)
{
vis[w[i].v]=1;
dfs(w[i].v);
}
}
end[t]=deep;
}
void update(int pos,int x,int n)
{
while(pos<=n)
{
c[pos]=c[pos]+x;
pos=pos+lowbit(pos);
}
}
int Sum(int pos)
{
int sum=0;
while(pos>=1)
{
sum=sum+c[pos];
pos=pos-lowbit(pos);
}
return sum;
}
int main()
{
int n,i,u,v,m,x;
char s[2];
memset(h,-1,sizeof(h));
memset(vis,0,sizeof(vis));
memset(apple,0,sizeof(apple)); //我们设0时有苹果,为1时没有苹果
memset(c,0,sizeof(c));
numw=0;
deep=0;
scanf("%d",&n);
for(i=1;n>i;i++)
{
scanf("%d %d",&u,&v);
insert(u,v); //建图
}
dfs(1); //深搜重新编号
for(i=1;n>=i;i++) //c数组初始化
{
update(i,1,n);
}
scanf("%d",&m);
for(i=1;m>=i;i++)
{
scanf("%s %d",s,&x);
if(s[0]=='C')
{
if(apple[x]==0)
{
update(start[x],-1,n);
apple[x]=1;
}
else
{
update(start[x],1,n);
apple[x]=0;
}
}
else
{
printf("%d\n",Sum(end[x])-Sum(start[x]-1)); //终止位置减去开始位置的值就是该节点上的数总和
}
}
return 0;
}