poj3321
来源:互联网 发布:攻壳模动队淘宝 编辑:程序博客网 时间:2024/05/21 09:02
题目大意:
给你一颗树,最初每个节点上都有一个苹果,有两种操作:修改(即修改某一个节点,修改时这一个节点苹果从有到无,或从无到有)和查询(查询某一个节点他的子树上有多少个苹果)。
由于此题数据比较大(N<=10^5),而且不是标准的二叉树,所以这里我们队每一个节点重新编号,另外为每一个节点赋一个左值和一个右值,表示这个节点的管辖范围。
感觉网上其他人写的代码都很复杂。。。。自己写了写,感觉用模板就可以了。。。。那些没用的操作完全可以简化具体做法:是做一次dfs,记下每个节点的开始时间Start[i]和结束时间End[i],那么对于i节点的所有子孙的开始时间和结束时间都应位于Start[i]和End[i]之间,另外用一个数组C[i]记录附加在节点i上的苹果的个数,然后用树状数组统计Start[i]到End[i]之间的附加苹果总数。这里用树状数组统计区间可以用Sum(Start[i])-Sum(End[i]-1)来计算。
#include <iostream>#include <cstdio>#include <set>#include <vector>#include<algorithm>using namespace std;const int Max = 1e5+1;vector<vector<int> > mp(Max);int End[Max];int start[Max];int Time;int c[Max],apple[Max];int n,m;void dfs(int u){ Time++; start[u] = Time; for(int i = 0; i <mp[u].size(); i++) { dfs(mp[u][i]); } End[u] = Time;}int lowbit(int x){ return x & -x;}void update(int x , int val){ while(x <= n) { c[x] += val; x += lowbit(x); }}int getsum(int x){ int sum = 0; while(x > 0) { sum += c[x]; x -= lowbit(x); } return sum;}int main(){ while(~scanf("%d",&n)) { Time = 0; for(int i = 1; i <= n-1; i++) { int a,b; scanf("%d%d",&a,&b); mp[a].push_back(b); } dfs(1); for(int i = 1; i <=n; i++) { update(i,1); apple[i] = 1; } scanf("%d",&m); while(m--) { char ch[12]; int t; scanf("%s%d",&ch,&t); if(ch[0] == 'Q') { printf("%d\n",getsum(End[t]) - getsum(start[t]-1)); } else { if(apple[t]) { update(start[t],-1); apple[t] = 0; } else { update(start[t],1); apple[t] = 1; } } } } return 0;}
0 0
- poj3321
- poj3321
- poj3321
- poj3321---Apple Tree
- poj3321 dfs+树状数组
- poj3321---树状数组
- POJ3321 Apple Tree
- poj3321 Apple Tree
- poj3321 树状数组
- POJ3321 Apple Tree
- POJ3321--Apple Tree
- POJ3321 Apple Tree
- POJ3321:Apple Tree
- poj3321(树状数组)
- poj3321解题报告
- POJ3321 Apple Tree
- POJ3321 Apple Tree
- poj3321 树状数组
- 基于mini2440开发板 Web服务器
- win7 激活方法
- UVA 11300-Spreading the Wealth(中位数)
- hdu 4866 主席树
- 常量指针和指针常量
- poj3321
- 黑马程序员--IO流之PrintStream:打印流
- 啊实打实的撒的啊实打实的
- poj1028-Web Navigation(水题)
- Win32API、MFC、.NET多线程并行求矩阵乘法(星星笔记)
- 按时可达上课了大事了的撒了解
- POJ 1815 (最小割的点集)
- 黑马程序员--IO流之其他
- 获取父类的泛型类型