HDU 1556 Color the ball(树状数组)
来源:互联网 发布:js获取useragent 编辑:程序博客网 时间:2024/05/11 13:34
HDU 1556 Color the ball(树状数组)
http://acm.hdu.edu.cn/showproblem.php?pid=1556
题意:
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个气球总共被涂色的次数。
分析:
本题用线段树可以很方便的解决。但是下面用树状数组的方法来解决:
初始时数组A[n]为全0。当我们给区间[a,b]内的气球涂颜色的时候,我们令A[a]这个点+1,然后令A[b+1]这个点-1。然后我们令sum(x)表示x这个气球点被涂色的总次数。(刚做这种题目可能比较难理解,强烈建议在纸上用一个简单的例子自己验证下)
举例:比如初始时我们想给区间[3,5]的气球上色,所以我们执行了add(3,1)和add(6,-1)。
然后我们执行sum(1)==0,sum(2)==0,sum(3)==1,sum(4)==1,sum(5)==1,sum(6)==0,sum(7)==0等。
你看,sum(x)是不是正好表示了第x个气球被涂色的次数? 其实我们可以这样理解,如果更新区间[3,5],那么我等于在3这个点+1,代表从3之后所有的点都增加了1。然后我们在6这个点-1表示从6之后所有的点都减少了1。所以达到了一个平衡的效果。最终实际+1的区间只是区间[3,5]内的数。
AC代码:390ms
<span style="font-size:18px;">#include<cstdio>#include<cstring>using namespace std;const int MAXN=100000+10;int c[MAXN];int lowbit(int x){ return x&(-x);}int sum(int x){ int res=0; while(x>0) { res +=c[x]; x-=lowbit(x); } return res;}void add(int x,int v){ while(x<MAXN) { c[x]+=v; x+=lowbit(x); }}int main(){ int n; while(scanf("%d",&n)==1&&n) { memset(c,0,sizeof(c)); for(int i=0;i<n;i++) { int a,b; scanf("%d%d",&a,&b); add(a,1); add(b+1,-1); } printf("%d",sum(1)); for(int i=2;i<=n;i++) printf(" %d",sum(i)); printf("\n"); }}</span>
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 [树状数组] [线段树]
- 关于Visual Studio 2013中strcpy函数的使用报错
- Microsoft ADO(ActiveX Data Object)用法浅析
- RMQ with Shifts(线段树单点跟新)
- IT潜力:站在大数据时代
- idapython 手册
- HDU 1556 Color the ball(树状数组)
- OLEDB操作EXCEL
- iOS中 常用的数据持久化方法
- memcpy实现
- C++构造函数和析构函数的调用顺序
- VC++下使用ADO操作数据库的智能指针_ConnectionPtr、_RecordsetPtr、_CommandPtr的方法
- 《数理统计学教程》序言(陈希孺)
- 阅读一款3D引擎的方法备忘
- hdu 1232 畅通工程(并查集)