您的位置:首页 > 移动开发

POJ 3321 Apple Tree (树状数组)

2013-03-25 11:07 465 查看
思路:用了时间戳,什么是时间戳?就是用begin[i]记录以i为根的,开始遍历的序号,end[i]记录以i为根,最后遍历的序号。

如下挫图:



从1开始遍历是,他是第一个遍历的,所以标为1,之后遍历所有子树后,到5的时候,5是第4个遍历的,所以5的begin值为4,而返回后,1的所有子树最大遍历标号就是5的begin值,所以2的end值为4,同理,1的end值为3的begin值为5

那么,可以发现,对于某个节点,我们查询他苹果数的时候,他所占的区域其实就是begin[i]~end[i],这样我们用树状数组求出sum(end[i])-sum(begin[i]-1)即可(当然包括begin[i]),对于更新,只要更新add(begin[i])就行了。

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn=100005;
int c[maxn],index,n;
int head[maxn],edge,begin[maxn],end[maxn];
int to[maxn<<1],next[maxn<<1];
bool flag[maxn],vis[maxn];
inline void addedge(int u,int v)
{
to[edge]=v,next[edge]=head[u],head[u]=edge++;
}
void init()
{
for(int i=1; i<=n; i++)
head[i]=-1,vis[i]=0;
edge=index=0;
}
void add(int x)
{
int val;
if(flag[x])
{
val=-1;
flag[x]=0;
}
else val=1,flag[x]=1;
while(x<=n)
c[x]+=val,x+=(x&-x);
}
int sum(int x)
{
int s=0;
while(x>0)
s+=c[x],x-=(x&-x);
return s;
}
void dfs(int now)
{
begin[now]=++index;
vis[now]=1;
for(int i=head[now]; ~i; i=next[i])
if(!vis[to[i]])
dfs(to[i]);
end[now]=index;
}
int main()
{
int i,u,v,m;
char ch[2];
while(~scanf("%d",&n))
{
init();
memset(c,0,sizeof(c));
for(i=0; i<n-1; ++i)
{
scanf("%d%d",&u,&v);
addedge(u,v);
addedge(v,u);
}
for(i=1; i<=n; i++)
{
add(i);
flag[i]=1;
}
dfs(1);
scanf("%d",&m);
while(m--)
{
scanf("%s",ch);
if(ch[0]=='Q')
{
scanf("%d",&u);
printf("%d\n",sum(end[u])-sum(begin[u]-1));
}
else
{
scanf("%d",&u);
add(begin[u]);
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: