hdu 1556 Color the ball(树状数组)
来源:互联网 发布:李小璐的淘宝店铺 编辑:程序博客网 时间:2024/05/18 17:04
题目分析
这道题我表示可以写的方法真的很多,比如线段树,我以前已经写过了,但是树状数组自己第一次写,树状数组反着推表示自己真的看了好久。
前缀和思想
#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>using namespace std;const int maxn = 1e5+100;int a[maxn];int main(){ int n; while(scanf("%d", &n) != EOF && n){ int l, r; memset(a, 0, sizeof(a)); for(int i = 0; i < n; i++){ scanf("%d%d", &l, &r); a[l]++, a[r+1]--; } for(int i = 1; i < n; i++){ a[i] += a[i-1]; printf("%d ", a[i]); } printf("%d\n", a[n] + a[n-1]); } return 0;}
树状数组写法1
因为树状数组维护的是前缀和,那么我们很明显就可以在l位置上加1,r+1位置上减一,这样每一个前缀和sum[1..i]表示的就是i位置染色的次数,跟上一个解法的思想一模一样。
#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>using namespace std;const int maxn = 1e5+100;int n;int C[maxn];inline lowbit(int x){ return x&-x;}void add(int x, int y){ while(x <= n){ C[x] += y; x += lowbit(x); }}int sum(int x){ int ret = 0; while(x > 0){ ret += C[x]; x -= lowbit(x); } return ret;}int main(){ while(scanf("%d", &n) != EOF && n){ memset(C, 0, sizeof(C)); int l, r; for(int i = 0; i < n; i++){ scanf("%d%d", &l, &r); add(l, 1); add(r+1, -1); } for(int i = 1; i < n; i++) printf("%d ", sum(i)); printf("%d\n", sum(n)); } return 0;}
树状数组写法2
树状数组中的每个节点都代表了一段线段区间,每次更新的时候,根据树状数组的特性可以把b以前包含的所有区间都找出来,然后把b之前的区间全部加一次染色次数。然后,再把a之前的区间全部减一次染色次数,这样就修改了树状数组中的[a,b]的区间染色次数,查询每一个点总的染色次数的时候,就可以直接向上统计每个父节点的值,就是包含这个点的所有区间被染色次数,这就是树状数组中向下查询,向上统计的典型应用。
#include <cstdio>#include <cstring>#include <iostream>#include <algorithm>using namespace std;const int maxn = 1e5+100;int n, C[maxn];inline int lowbit(int x){ return x&(-x);}void add(int x, int y){ while(x > 0){ C[x] += y; x -= lowbit(x); }}int sum(int x){ int ret = 0; while(x <= n){ ret += C[x]; x += lowbit(x); } return ret;}int main(){ while(scanf("%d", &n) != EOF && n){ memset(C, 0, sizeof(C)); int l, r; for(int i = 0; i < n; i++){ scanf("%d%d", &l, &r); add(l-1, -1); add(r, 1); } for(int i = 1; i < n; i++) printf("%d ", sum(i)); printf("%d\n", sum(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 the ball(树状数组)
- HDU Color the ball (树状数组)
- hdu Color the ball树状数组
- color the ball -- hdu -- 树状数组
- Hdu--1556--Color the ball(树状数组最简单运用)
- HDU--1556 -- Color the ball [树状数组] [线段树]
- NYOJ-传纸条(一)、探寻宝藏【双路(线)DP】
- JSlider实现缩放照片的大小
- iOS多线程总结
- 项目中可能遇到的问题
- 【笔记】电商网站, 用户可以自定义推荐橱窗的个数, 实现商品推荐的大体思路
- hdu 1556 Color the ball(树状数组)
- web回顾(4.25)
- oracle执行update和insert语句卡住不动
- 深入理解C++动态内存管理:malloc/free和new/delete的区别和联系
- c++: dynamic_cast详解
- 迷宫
- java——网络编程
- 剑指offer_面试题10_二进制中1的个数(位运算)
- github+hexo搭建个人博客