hdu 1556 Color the ball (树状数组)
来源:互联网 发布:fade to black知乎 编辑:程序博客网 时间:2024/06/10 04:27
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,输入结束。
Output
每个测试实例输出一行,包括N个整数,第I个数代表第I个气球总共被涂色的次数。
Sample Input
3
1 1
2 2
3 3
3
1 1
1 2
1 3
0
Sample Output
1 1 1
3 2 1
题解
典型的区间修改单点查询。用树状数组又快又好。这里新学习了一种高级方法,能够在树状数组上进行区间修改。方法是存数的时候就存比前一个数多的那部分,由前缀和来构成这个数,比如先存了第一个数a,那么存第二个数b时就add(b-a, delta)。要取出这个数也不再是sum(b) - sum(b - 1),而是直接sum(b)。那么如何进行区间修改?方法是差分,将l~r的一头一尾分别加上、减去修改的值。这是由于树状数组的性质,在修改时是向上叠加的前缀和的样式,所以在l处加上这个值,后面的数也都加上了这个值;在r - 1处减去这个值,就避免了超出区间的部分也加上了这个值。
代码
#include <cstdio>#include <cstring>#include <algorithm>using namespace std;int n, cnt = 0, tree[1000010];int lowbit(int x) { return x & (- x);}void modify(int x, int delta) { while(x <= n) { tree[x] += delta; x += lowbit(x); }}int query(int x) { int sum = 0; while(x) { sum += tree[x]; x -= lowbit(x); } return sum;}int main() { while(~ scanf("%d", &n) && n) { memset(tree, 0, sizeof(tree)); int l, r; for(int i = 1; i <= n; i ++) { scanf("%d %d", &l, &r); modify(l, 1); modify(r + 1, -1); } for(int i = 1; i < n; i ++) printf("%d ", query(i)); printf("%d\n", query(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(树状数组)
- 文章标题
- 关于外网如何访问内网资源的解决办法
- 内存分配(首次适应算法)
- C
- 括号匹配 栈的应用
- hdu 1556 Color the ball (树状数组)
- Android笔记(21)网络加载圆形图片
- Java -- BigDecimal类
- Android中SQLite的数据库版本升级详解
- 《Drools7.0.0.Final规则引擎教程》第4章 4.3 定时器
- flume简介与安装配置
- spring学习之---创建Bean的三种方式
- 爬图片URL
- Java实现冒泡排序算法