树状数组练习

1.校门外的树

详见一本通

给定[1,n]的区间,进行m次操作,每次在[l,r]范围内种一种树,给定任意[l0,r0]求种植的树有多少种

问题转化,不妨把种树区间[l,r]看成括号序列(),对于询问区间[l,r]:

r的左侧有多少个"(",代表r的左侧存在的树的总数!

l的左侧有多少个")",代表l的左侧已经种下了多少种树,这些树不会出现在[l,r]内,需要减掉;

所以可以维护两个树状数组,T1维护左括号序列,T2维护右括号序列:

k=1 更新[l,r]区间内的值,updateT1(l,1),updateT2(r,1);

k=2 就是用r的"("减去l的")",即sumT1(r)-sumT2(l-1),(因为sum函数是闭区间,如果减去l,当只有l处存在一种树时的情况被忽落了!)

AC code:

#include<cstdio>
using namespace std;
const int maxn=5e4+10;
int T1[maxn],T2[maxn],n,m;
int lowbit(int x)
{
return x & (-x);
}
void updateT1(int x,int k)
{
while(x<=n)
{
T1[x]+=k;
x+=lowbit(x);
}

}
void updateT2(int x,int k)
{
while(x<=n)
{
T2[x]+=k;
x+=lowbit(x);
}
}
int queryT1(int x)
{
int res=0;
while(x>0)
{
res+=T1[x];
x-=lowbit(x);
}
return res;
}
int queryT2(int x)
{
int res=0;
while(x>0)
{
res+=T2[x];
x-=lowbit(x);
}
return res;
}
int main()
{
int k,l,r;
scanf("%d %d",&n,&m);
for(int i=1;i<=m;i++)
{
scanf("%d %d %d",&k,&l,&r);
if(k==1)
{
updateT1(l,1);
updateT2(r,1);
}
if(k==2)
{
printf("%d\n",queryT1(r)-queryT2(l-1));
}
}
return 0;

}

2.数星星:

由于给定有序序列,只需要求有多少x坐标更小的星星即可!

#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
const int maxn=50000;
int c[maxn],n,ans[maxn],m=32001;
struct node{
int x,y;
}star[maxn];
int lowbit(int x)
{
return x & (-x);
}
void update(int x,int k)
{
while(x<=m)
{
c[x]+=k;
x+=lowbit(x);
}

}
int query(int x)
{
int res=0;
while(x>0)
{
res+=c[x];
x-=lowbit(x);
}
return res;
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d %d",&star[i].x,&star[i].y);
for(int i=1;i<=n;i++)
{
int v=star[i].x+1;
int sum=query(v);
update(v,1);
ans[sum]++;
}
for(int i=0;i<=n-1;i++)
printf("%d\n",ans[i]);
return 0;
}

转载于:https://www.cnblogs.com/little-cute-hjr/p/11484447.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值