HDU1556 树状数组,线段树区间更新两种方法(主要树状数组)
来源:互联网 发布:gentoo linux 编辑:程序博客网 时间:2024/05/21 04:40
树状数组
#include <stdio.h>#include <string.h>const int MAXN=110000;int n,c[MAXN];int lowbit(int x)//计算2^k{ x=x&-x; return x;}void update(int num,int val)//向下查询,num是要更新的子节点,val是要修改的值{ while(num>0) { c[num]+=val; num-=lowbit(num); }}int getSum(int num)//向上统计每个区间被染色的次数{ int sum=0; while(num<=n) { sum+=c[num]; num+=lowbit(num); } return sum;}int main(){ int a,b; while(scanf("%d",&n),n) { memset(c,0,sizeof(c)); for(int i=0;i<n;i++) { scanf("%d%d",&a,&b); //将b以下区间+1 update(b,1); //将a以下区间-1 update(a-1,-1); } for(int j=1;j<n;j++) { printf("%d ",getSum(j)); } printf("%d\n",getSum(n)); } return 0;}
线段树
#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;int ans[1000000],n;struct node{ int l,r,n;} a[1000000];void init(int l,int r,int i){ a[i].l = l; a[i].r = r; a[i].n = 0; if(l!=r) { int mid = (l+r)>>1; init(l,mid,2*i); init(mid+1,r,2*i+1); }}void insert(int i,int x,int y){ if(a[i].l == x && a[i].r == y)//找到要刷的气球区间,更新其被刷的次数+1 a[i].n++; else { int mid = (a[i].l+a[i].r)>>1; if(y<=mid) insert(2*i,x,y); else if(x>mid) insert(2*i+1,x,y); else { insert(2*i,x,mid); insert(2*i+1,mid+1,y); } }}void add(int x){ int i; for(i = a[x].l; i<=a[x].r; i++)//该区间所有编号都被刷了一次 ans[i]+=a[x].n; if(a[x].l == a[x].r) return; add(2*x); add(2*x+1);}int main(){ int x,y,i; while(~scanf("%d",&n),n) { init(1,n,1); for(i = 1; i<=n; i++) { scanf("%d%d",&x,&y); insert(1,x,y); } memset(ans,0,sizeof(ans)); add(1); printf("%d",ans[1]); for(i = 2; i<=n; i++) printf(" %d",ans[i]); printf("\n"); } return 0;}
这里转载了两个别人的代码。感觉树状数组简单好多。。。
阅读全文
0 0
- HDU1556 树状数组,线段树区间更新两种方法(主要树状数组)
- hdu1556树状数组更新区间
- hdu1556(树状数组/线段树,区间修改,点查询)
- HDU1556:Color the ball(线段树区间更新单点求值)&&树状数组解法
- hdu1556 color the ball 树状数组区间更新单点查询(附线段树做法)与二维扩展
- hdu1556(树状数组)
- hdu1556树状数组&&线段树2种做法
- 树状数组:HDU1556 Color the ball 【区间更新,单点查询]
- HDU1556 Color the ball【树状数组】【区间更新】
- hdu1556-树状数组 一维 区间更新 单点查询
- 【树状数组-区间更新】hdu1556 Color the ball
- hdu1556 Color the ball【树状数组 || 线段树 || 技巧*区间修改】
- hdu1556 树状数组 区间修改,点查询
- (树状数组)hdu1556 Color the ball(区间更新,单点查询)
- HDU1556——Color the ball(区间更新OR树状数组)
- HDU1556 Color the ball 树状数组(区间更新单点求值)
- hdu1556——树状数组水题练习(区间更新单点求和)
- 树状数组 区间更新
- 按照层次遍历并打印二叉树
- ReactNative初体验
- 实习前十天总结
- 学习Markdown
- LeetCode
- HDU1556 树状数组,线段树区间更新两种方法(主要树状数组)
- Java注解
- numpy的random模块
- C++中不能重载的运算符
- Spark Shuffle初探
- 电脑卡慢的原因
- 理解HTTP缓存和304状态码
- 【LBS】基于地理位置的搜索之微信 附近的人 简单实现
- Java四种线程池的使用