POJ3321 Apple Tree
来源:互联网 发布:阿里云邮箱注册不了 编辑:程序博客网 时间:2024/05/02 21:04
说实话这个题写得挺郁闷的,刚开始在Codevs上能过,但在POJ却超时,最后发现竟是iostream惹的祸……换成标准输入输出后就AC了。
言归正传,该题的主要思路为:先进行后根遍历,同时记录节点分管的区域,然后利用树状数组求解。
在程序中:a[]为后根遍历序列,由于初始值均为1,故直接定义即可,不需额外操作。利用vector记录儿子节点。backorder()是后根遍历过程,递归中用cnt来确定某一节点的儿子区间(由后根遍历特点可知父亲在最后且儿子首尾相连),至于lowbit()、change()、sum(),均为树状数组的基本操作,不再解释。
代码如下:
#include<iostream>#include<cstdio>#include<vector>#include<cstring>using namespace std;const int maxn=100005;struct appletype{ int l,r;}apple[maxn];vector<int> vec[maxn];int n,m,cnt=1,c[maxn],a[maxn];void backorder(int root){ vector<int> :: iterator i; apple[root].l=cnt; for (i=vec[root].begin();i!=vec[root].end();++i) backorder(*i); apple[root].r=cnt++; }int lowbit(int i){ return i&(-i);}void change(int x){ int i; if (a[x]) for (i=x;i<=cnt;i+=lowbit(i)) c[i]++; else for (i=x;i<=cnt;i+=lowbit(i)) c[i]--; }int sum(int n){ int s=0; while (n>0) { s+=c[n]; n-=lowbit(n); } return s;}void init(){ memset(a,1,sizeof(a)); scanf("%d",&n); for (int i=1;i<=n-1;++i) { int u,v; scanf("%d%d",&u,&v); vec[u].push_back(v); } backorder(1); for (int i=1;i<=n;++i) change(i); scanf("%d",&m); for (int i=1;i<=m;++i) { char mark; cin>>mark; if (mark=='Q') { int x; scanf("%d",&x); int ans=sum(apple[x].r)-sum(apple[x].l-1); printf("%d\n",ans); } else { int x; scanf("%d\n",&x); a[apple[x].r]=(a[apple[x].r]+1)%2; change(apple[x].r); } }}int main(){ init(); return 0;}
0 0
- poj3321---Apple Tree
- POJ3321 Apple Tree
- poj3321 Apple Tree
- POJ3321 Apple Tree
- POJ3321--Apple Tree
- POJ3321 Apple Tree
- POJ3321:Apple Tree
- POJ3321 Apple Tree
- POJ3321 Apple Tree
- POJ3321 Apple Tree
- poj3321 Apple Tree
- poj3321 Apple Tree
- poj3321 Apple Tree
- POJ3321 Apple Tree
- poj3321 Apple Tree
- poj3321 Apple Tree
- 【POJ3321】Apple Tree
- poj3321 Apple Tree
- 如何使用ApkPlug插件化我的第一个应用
- C\C++ 向下\向上取整函数 floor() ceil()
- eclipse的java源码关联
- 欧拉计划(9)Special Pythagorean triplet
- nagios二次开发(六)---nagiosql原理及主要文件的介绍
- POJ3321 Apple Tree
- Java反射机制分析指南
- Linux命令行(console)屏幕分辨率调整
- Adaboost算法
- 黑马程序员-----java5的新特性
- 九度OJ 1202 排序
- 一起talk Vim吧(第六回:Vim刀法之乾坤大挪移)
- java中set集合的总结
- PCA算法