HDU 1556 Color the ball - from lanshui_Yang
来源:互联网 发布:梦幻西游须弥真言数据 编辑:程序博客网 时间:2024/05/16 18:25
当N = 0,输入结束。
31 12 23 331 11 21 30
1 1 13 2 1
这是一道典型的一维树状数组的变形,普通的一维树状数组的用途是:单点更新,区间求值。而这道题的则是用到树状数组的另一个用途:区间更新,单点求值。原理如下:
假设原始数组的各个元素为a[1] , a[2] ,…… a[n] , 那么 d[n] = a[1] + a[2] + …… + a[n] 求的就是前n项和,这就是树状数组的第一个用途:单点更新,区间求和。
然后,稍微做些改动,假设原始数组的各个元素为a[1] - 0 , a[2] - a[1] , a[3] - a[2] ,……,a[n] - a[n - 1] , 那么此时的前n项和 d[n] = a[n] ,也就是说,现在原始数组的前n项和d[n] 就等于单点的值a[n] 了 ,大家看到这里是不是就有些明白了呢?
接着,如果你想时区间[ a[m] …… a[n] ] 中的所有值都 + Val ,那么只需将原始数组的第m项 (a[m] - a[m - 1] ) 加上 Val , 和将第n + 1项 (a[n + 1] - a[n]) 减去 Val 就可以了, 这样当 m <= i <= n 时 ,
数列的前 i 项和:
d[i] = (a[1] - 0) + (a[2] - a[1]) + (a[3] - a[2]) + …… + (a[m] - a[m - 1] + val) + (a[m + 1] - a[m]) + …… + (a[i] - a[i - 1] ) = a[i] + val 。
同理当 i > n 时 ,d[i] 等于原来的 a[i] 。看到这里,大家是不是就豁然开朗啦。注意一点,这里a[1] …… a[n] 的初始值均为0 !!
下面请看代码:
#include<iostream>#include<cstring>#include<string>#include<cstdio>#include<cmath>#include<algorithm>#include<queue>using namespace std ;const int MAXN = 1e5 + 5 ;int C[MAXN] ;int n ;int lowbit (int x){ return x & -x ;}void add(int x , int d){ while(x <= n) { C[x] += d ; x += lowbit(x) ; }}int sum(int x){ int sumt = 0 ; while (x > 0) { sumt += C[x] ; x -= lowbit(x) ; } return sumt ;}int main(){ while (scanf("%d" , &n) != EOF) { if(n == 0 ) break ; memset(C , 0 , sizeof(C)) ; int t = n ; int i ; while ( t-- ) { int a , b ; scanf("%d%d", &a , &b) ; add(a , + 1) ; add(b + 1 , -1) ; } for(i = 1 ; i <= n ; i ++) { printf("%d" , sum(i)) ; if(i < n) printf(" ") ; } puts("") ; } return 0 ;}
- HDU 1556 Color the ball - from lanshui_Yang
- hdu 1556 color the ball
- hdu 1556Color 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
- Unknown protocol to name node: org.apache.hadoop.mapred.JobSubmissionProtocol
- VC中UpdateData()函数的使用
- 设置PHP 脚本执行超时的时间
- 用Chrome浏览器打开本地DOM应用,报Load page error,页面不跳转
- XML文档规则
- HDU 1556 Color the ball - from lanshui_Yang
- HDU 1051 Wooden Sticks(贪心算法)
- 11181 - Probability|Given
- 超强的参考资料让你的android开发如鱼得水
- IO流异常文件日志
- 编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推
- Exchange Server 2013新功能介绍
- 如何将EXCEL的多列数据叠加合并到一列
- 集团企业网站群建设发展趋势