HDU 1556 Color the ball(树状数组)
来源:互联网 发布:淘宝充值软件 编辑:程序博客网 时间:2024/06/05 16:24
Color the ball
Time Limit: 9000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 23345 Accepted Submission(s): 11353
Problem Description
N个气球排成一排,从左到右依次编号为1,2,3....N.每次给定2个整数a b(a <= b),lele便为骑上他的“小飞鸽"牌电动车从气球a开始到气球b依次给每个气球涂一次颜色。但是N次以后lele已经忘记了第I个气球已经涂过几次颜色了,你能帮他算出每个气球被涂过几次颜色吗?
Input
每个测试实例第一行为一个整数N,(N <= 100000).接下来的N行,每行包括2个整数a b(1 <= a <= b <= N)。
当N = 0,输入结束。
当N = 0,输入结束。
Output
每个测试实例输出一行,包括N个整数,第I个数代表第I个气球总共被涂色的次数。
Sample Input
31 12 23 331 11 21 30
Sample Output
1 1 13 2 1
Author
8600
Source
HDU 2006-12 Programming Contest
【思路】
这题第一次做的时候是为了学会区间更新、单点查询的操作,尝试好久去理解题解亦似懂非懂,第二次做才确实理解了,真心觉得这题并不是拿来学区间更新、单点查询的好题,因为它有个巧合,容易误导人。
不同于单点更新、区间查询,我们在这里要将树状数组反过来用,数组维护的不是元素本身,而是相邻元素的差值,我们称之为差分数组,即c[1]=a[1]-a[0](视a[0]为0吧),c[2]=a[2]-a[1],c[3]=a[3]-a[2],...,于是可用sum函数来求单点a[i]的值,由于要统一修改的是某一段[a,b],给它加上x,那么这段区间内部的差分就不变,变的是两头和外面元素的差值,即c[a]要加上这个x,给c[b]减掉这个x,向高层传递以维护树状数组的统一性,这时前缀和的含义依然是单点的值。
对于单点更新、区间查询,我们很容易理解sum函数是通过将前缀区间分割成若干后缀后求和来得到前缀和的,而modify修改操作,则是将对单点修改带来的影响上传至更高层次,以便之后计数用的,所以我们有个思维惯性认为这道题的第二处单点修改是为了消除第一次带来的这个影响。巧合的是在这里初始本应求的差分数组,因为相邻两个元素之间都是0,继而差值是0而直接没有求了,也就导致了很多人的博客忽略了这一点大谈区间修改、单点查询,把树状数组的原理也搞得神秘不已、难以理解。在此记之,希望因为这道题而来访的人能少走弯路。
【代码】
#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int MAXN=1e5+5;int n;int a[MAXN];int lowbit(int x){ return (x&-x);}void modify(int x,int num){ while(x<=n){ a[x]+=num; x+=lowbit(x); }}int sum(int x){ int ans=0; while(x>0){ ans+=a[x]; x-=lowbit(x); } return ans;}int main(){ while(scanf("%d",&n)==1&&n!=0){ memset(a,0,sizeof(a)); for(int i=1;i<=n;i++){ int a,b; scanf("%d %d",&a,&b); modify(a,1); modify(b+1,-1); } for(int i=1;i<=n;i++){ if(i!=1)printf(" "); printf("%d",sum(i)); } printf("\n"); } return 0;}
阅读全文
0 0
- HDU 1556 color the ball 树状数组
- hdu 1556 Color the ball (树状数组)
- hdu 1556 Color the ball 树状数组
- HDU 1556 Color the ball(树状数组)
- HDU 1556--Color the ball【树状数组】
- hdu 1556 Color the ball 树状数组
- hdu 1556 Color the ball树状数组
- 树状数组-HDU-1556-Color the ball
- hdu 1556 Color the ball(树状数组)
- HDU 1556 Color the ball(树状数组)
- HDU 1556 Color the ball (树状数组)
- hdu 1556 Color the ball(树状数组)
- hdu 1556 Color the ball(树状数组)
- HDU 1556 Color the ball(树状数组)(填坑)
- HDU 1556 Color the ball (树状数组简单应用)
- HDU 1556 Color the ball (简单树状数组)
- hdu 1556 Color the ball (扫描线+树状数组)
- hdu 1556 Color the ball(树状数组)
- 学无止境-1
- QMessageBox
- java命名规范
- 认认真真做事,勤勤恳恳做人
- SSM+MAVEN+RESTFUL构建
- HDU 1556 Color the ball(树状数组)
- 淘宝首页交互1--热点图标跳动
- ScrollView嵌套RecyclerView滑动卡顿,无惯性
- MySQL(1)使用前的准备(安装版的安装步骤)
- 利用js解析php的表单数据
- Android面试——内存泄漏
- leetcode646 Maximum Length of Pair Chain java解题代码
- 堆与栈的区别
- 线程