您的位置:首页 > 其它

HDU 1556 Color the ball(树状数组,基础,气球染色问题)

2016-08-18 17:12 871 查看

http://acm.split.hdu.edu.cn/showproblem.php?pid=1556

Color the ball

Time Limit: 9000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 17173    Accepted Submission(s): 8584

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

 

[align=left]Author[/align]
8600
 

[align=left]Source[/align]
HDU 2006-12 Programming Contest 

题意:

看得懂就行。

思路:

最初采用的是向上更新,向下统计的方法(宇神讲的方法)。----Code 1

树状数组中的每个节点都代表了一段线段区间,

每次更新,根据其特性可以把 a 以前包含的区间找出来,然后把 a 以前的区间全部加一次染色次数;

再把 b 以前的区间全部减一次染色次数,这样就修改了树状数组中的[a,b]的区间染色次数。

后来就试试向下更新,向上统计的代码。-----Code 2

 

Code 1:(时间较快)

655MS 1808K 

#include<stdio.h>
#include<cstring>
const int MYDD=1103+1e5;

int Balloon[MYDD];
int LowBit(int x) {
return (-x)&x;
}

void UpDate(int node,int value,int n) {
while(node<=n) {//向上进行节点的更新
Balloon[node]+=value;
node+=LowBit(node);
}
}

int GetSum(int node) {
int ans=0;//向下统计
while(node>0) {
ans+=Balloon[node];
node-=LowBit(node);
}
return ans;
}

int main() {
int N;
while(1) {
scanf("%d",&N);
if(!N) break;
memset(Balloon,0,sizeof(Balloon));
for(int j=0; j<N; j++) {
int a,b;
scanf("%d%d",&a,&b);
UpDate(a,1,N); // a以下区间加 +1
UpDate(b+1,-1,N);// b 以下区间 -1
}
for(int j=1; j<N; j++)
printf("%d ",GetSum(j));
printf("%d\n",GetSum(N));
}
return 0;
}


Code 2:

702MS 1812K 
#include<stdio.h>
#include<cstring>
const int MYDD=1103+1e5;

int Balloon[MYDD];
int LowBit(int x) {
return (-x)&x;
}

void UpDate(int node,int value) {
while(node>0) {//向下进行节点的更新
Balloon[node]+=value;
node-=LowBit(node);
}
}

int GetSum(int node,int n) {
int ans=0;//向上统计
while(node<=n) {
ans+=Balloon[node];
node+=LowBit(node);
}
return ans;
}

int main() {
int N;
while(1) {
scanf("%d",&N);
if(!N) break;
memset(Balloon,0,sizeof(Balloon));
for(int j=0; j<N; j++) {
int a,b;
scanf("%d%d",&a,&b);
UpDate(a-1,-1); // a 以下区间 -1
UpDate(b,1); // b以下区间加 +1
}
for(int j=1; j<N; j++)
printf("%d ",GetSum(j,N));
printf("%d\n",GetSum(N,N));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: