poj 3321 Apple Tree
来源:互联网 发布:淘宝直通车如何操作 编辑:程序博客网 时间:2024/06/06 03:32
题意:一颗苹果树,树上有n个树枝节点,一个节点有一个苹果,有n-1个树枝。模型是即n个点n-1条边的树,叉数不定。对这棵树可进行两种操作,其中Q x是询问第x节点上子树的苹果个数,C x是如果x节点上有苹果,就会被拿掉,如果没有,树就会长出苹果。
思路:本题关键就在于建立树和树状数组的映射关系。对于每一个树枝节点,我们需要知道的就是它的管辖范围,即它下面包括自己一共管了多少个节点,并且指定到具体区间,那么首先就需要DFS遍历这个树,在DFS内使用一个累加器记录遍历节点的个数,在递推到某个节点的时候累加器的值就是这个节点所管辖范围的起始值即下限,当又一次回溯回这个节点的时候累加器的值就是这个节点所管辖范围的上限。这个节点的下限就是这个节点在树状数组中的位置,计算query(high)- query(low-1)可得到该节点所有苹果个数。
下面这个图有助于理解:
#include <iostream>#include <algorithm>#include <cstdlib>#include <cstring>#include <cstdio>using namespace std;struct node{ int v,next;}d[1000000];struct NODE{ int low,high;}p[100010];int head[100010];int vis[100010];int atree[100010],a[100010];int step,n;void DFS(int u){ vis[u]=1; step++; p[u].low=step; for(int i=head[u];i!=-1;i=d[i].next) { if(!vis[d[i].v]) { DFS(d[i].v); } } p[u].high=step;}void add(int t,int d){ while(t<=n) { atree[t] += d; t+=t&-t; }}int query(int t){ int sum=0; while(t>0) { sum += atree[t]; t-=t&-t; } return sum;}int main(){ int m,x; int cnt=0; int u,v; char c[2]; step=0; memset(head,-1,sizeof(head)); memset(vis,0,sizeof(vis)); memset(atree,0,sizeof(atree)); scanf("%d",&n); for(int i=0;i<n-1;i++) { scanf("%d%d",&u,&v); d[cnt].next=head[u]; d[cnt].v=v; head[u]=cnt++; d[cnt].next=head[v]; d[cnt].v=u; head[v]=cnt++; } DFS(1); for(int i=1;i<=n;i++) { add(i,1); a[i]=1; } scanf("%d%*c",&m); while(m--) { scanf("%s",c); if(c[0]=='C') { scanf("%d%*c",&x); if(a[p[x].low]==1){ add(p[x].low,-1); a[p[x].low]=0; } else { add(p[x].low,1); a[p[x].low]=1; } } else { scanf("%d%*c",&x); int ans=query(p[x].high)-query(p[x].low-1); printf("%d\n",ans); } } return 0;}
0 0
- POJ 3321 Apple Tree
- POJ 3321 Apple Tree
- poj 3321 Apple Tree
- POJ 3321 Apple Tree
- Poj 3321 Apple Tree
- poj 3321 apple tree
- poj 3321 Apple Tree
- poj 3321 Apple Tree
- POJ 3321 Apple Tree
- POJ--3321--Apple Tree
- POJ-3321-Apple Tree
- poj 3321 Apple Tree
- POJ 3321 Apple Tree
- POJ 3321 Apple Tree
- POJ 3321 Apple Tree
- POJ 3321 Apple Tree
- POJ:3321 Apple Tree
- POJ 3321 Apple Tree
- layout_graviry和gravity的区别及需要注意的问题
- 代码段,数据段,BSS段, 堆,栈, 参数
- Tree 递归
- Mac os x captain 10.11.1 安装boost库 及配置Xcode
- System V 中内存共享的简单实例
- poj 3321 Apple Tree
- Linux---有关dig命令的实用脚本
- 数据采集主要代码
- 中央剪切图片
- 彻底理解MapReduce shuffle过程原理
- PE导出表笔记
- java synchronized 关键字
- 偏差和方差的区别
- 3小时做完3天工作,她是用了什么办法做到的?