题目链接:http://acm.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): 23008 Accepted Submission(s): 11182
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,输入结束。
当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
Author
8600
把单点看成区间查询而已 没什么不一样的
线段树基础
#include <iostream>
#include <queue>
#include <stdio.h>
#include <stdlib.h>
#include <stack>
#include <limits>
#include <string>
#include <string.h>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <math.h>
using namespace std;
#define maxn 500005
int flag;
struct xjy
{
int left;
int right;
int target;
int lazy;
int sum;
};
xjy tree[maxn<<2];
int a[maxn];
int n,m;
int t;
void show(int i,int left,int right)
{
if(left==right)
{
printf("%d %d %d %d %d\n",tree[i].sum,tree[i].left,tree[i].right,tree[i].lazy,tree[i].target);
return;
}
int mid=(left+right)>>1;
show(i<<1,left,mid);
show(i<<1|1,mid+1,right);
printf("%d %d %d %d %d\n",tree[i].sum,tree[i].left,tree[i].right,tree[i].lazy,tree[i].target);
}
void build(int i,int left,int right)
{
if(left==right)
{
tree[i].sum=0;
tree[i].left=left;
tree[i].right=right;
a[left]=i;
return;
}
int mid=(left+right)>>1;
build(i<<1,left,mid);
build(i<<1|1,mid+1,right);
tree[i].sum=0;
tree[i].left=left;
tree[i].right=right;
}
void updateregion(int i,int left,int right)
{
if(tree[i].left==left&&tree[i].right==right)
{
tree[i].lazy=1;
tree[i].target+=1;
return;
}
int mid=(tree[i].left+tree[i].right)>>1;
if(right<=mid)
updateregion(i<<1,left,right);
else if(left>mid)
updateregion(i<<1|1,left,right);
else
{
updateregion(i<<1,left,mid);
updateregion(i<<1|1,mid+1,right);
}
}
int queryregion(int i,int left,int right)
{
if(tree[i].lazy)
{
tree[i].lazy=0;
tree[i<<1].lazy=1;
tree[i<<1].target+=tree[i].target;
tree[i<<1|1].lazy=1;
tree[i<<1|1].target+=tree[i].target;
tree[i].sum+=tree[i].target;
}
if(tree[i].left==tree[i].right)
{
return tree[i].sum;
}
int mid=(tree[i].left+tree[i].right)>>1;
if(right<=mid)
return queryregion(i<<1,left,right);
else if(left>mid)
return queryregion(i<<1|1,left,right);
else
{
return queryregion(i<<1,left,mid);
return queryregion(i<<1|1,mid+1,right);
}
}
int main()
{
while(~scanf("%d",&n)&&n)
{
for(int i=0;i<maxn;i++)
{
tree[i].lazy=0;
tree[i].sum=0;
tree[i].target=0;
a[i]=0;
}
build(1,1,n);
for(int step=1;step<=n;step++)
{
int x,y;
scanf("%d%d",&x,&y);
updateregion(1,x,y);
}
for(int i=1;i<=n;i++)
{
printf("%d",queryregion(1,i,i));
if(i!=n)
printf(" ");
else
printf("\n");
}
}
}