题意:
N个气球
涂色:将【l,r】涂一次颜色
查询:最后输出每个气球被涂了多少次色
思路:
查询:区间维护加法和,查询到叶子
修改:维护可叠加标记lazy,每次区间内气球的次数+=1
难度:0.6
1263ms
#include<stdio.h>
#include<math.h>
#include<iostream>
using namespace std;
const int inf=0x3f3f3f;
struct Stree
{
int val;
int lazy;
} sts[4*100005]; //开4倍
int pushup(int root)
{
sts[root].val=sts[root<<1].val+sts[root<<1|1].val;
}
int pushdown(int root)
{
if(sts[root].lazy!=0)
{
sts[root<<1].lazy+=sts[root].lazy;
sts[root<<1|1].lazy+=sts[root].lazy;
sts[root<<1].val+=sts[root].lazy;
sts[root<<1|1].val+=sts[root].lazy;
sts[root].lazy=0;
}
}
void build(int l,int r,int root)//根节点从1开始吧
{
if(l==r)//到达子节点
{
sts[root].val=0;
}
else
{
sts[root].val=sts[root].lazy=0;//没了这句会WA,清空lazy跟val
int mid=(l+r)>>1;//(l+r)/2
build(l,mid,root<<1);
build(mid+1,r,root<<1|1);
pushup(root);//更新本节点
}
}
int query(int nowl,int nowr,int ql,int qr,int root)
{
if(nowl>=ql&&nowr<=qr)
{
return sts[root].val;
}
pushdown(root);
int mid=(nowl+nowr)>>1;
int ans=0;
if(ql<=mid)ans+=query(nowl,mid,ql,qr,root<<1);
if(qr>mid)ans+=query(mid+1,nowr,ql,qr,root<<1|1);
return ans;
}
void update(int nowl,int nowr,int ul,int ur,int root,int addval)//nowl,nowr 当前区间 ul,ur 需修改的区间
{
if(ul<=nowl&&ur>=nowr)//当前区间是修改区间的子区间
{
sts[root].val+=addval;
sts[root].lazy+=addval;
return ;
}
int mid=(nowl+nowr)>>1;
pushdown(root);
if(ul<=mid) update(nowl,mid,ul,ur,root<<1,addval);//左子树与修改区间有交集
if(ur>mid) update(mid+1,nowr,ul,ur,root<<1|1,addval);
pushup(root);
}
void op(int n);
int main()
{
int n;
while(cin>>n)
{
if(n==0)break;
build(1,n,1);
//op(n);
int a,b;
int T=n;
while(T--)
{
scanf("%d %d",&a,&b);
update(1,n,a,b,1,1);
}
printf("%d",query(1,n,1,1,1));
for(int i=2; i<=n; i++)
{
printf(" %d",query(1,n,i,i,1));
}
printf("\n");
}
}
void op(int n)
{
printf("\n///\n");
int up=pow(2.0,ceil(log10((double)n)/log10(2.0))+1)-1;
for(int i=1; i<=up; i++)
{
printf("%d ",sts[i].val);
int t=log10((double)i+1.0)/log10(2.0);
if(pow(2.0,t)==i+1)
printf("\n");
}
printf("///\n");
}