【ssl1502】校门外的树(加强版)【树状数组】

Description

校门外有很多树,有苹果树,香蕉树,有会扔石头的,有可以吃掉补充体力的……
如今学校决定在某个时刻在某一段种上一种树,保证任一时刻不会出现两段相同种类的树,现有两个操作:
K=1,读入l,r表示在l~r之间种上的一种树
K=2,读入l,r表示询问l~r之间能见到多少种树
(l,r>0)

Input

第一行n,m表示道路总长为n,共有m个操作
接下来m行为m个操作

Output

对于每个k=2输出一个答案

Sample Input

5 4
1 1 3
2 2 5
1 2 4
2 3 5

Sample Output

1
2
Hint

范围:20%的数据保证,n,m<=100
60%的数据保证,n <=1000,m<=50000
100%的数据保证,n,m<=50000

分析

这题也是模板题,貌似可以用线段树做,但是我用了树状数组。
这题要开两个树状数组,分别写两个操作函数,表示修改权值和前缀和。
分别修改l域和r域

上代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
typedef long long ll;
using namespace std;
int n,m,k,l,r,c[100001],a[100001];
int lowbit(int x)
{
	return x&(-x);
}
void change(int x)
{
	for(;x<=n;x+=lowbit(x))
	{
		c[x]++;
	}
}
int ask(int x)
{
	int ans=0;
	for(;x>0;x-=lowbit(x))
	{
		ans+=c[x];
	}
	return ans;
}
void change2(int x)
{
	for(;x<=n;x+=lowbit(x))
	{
		a[x]++;
	}
}
int ask2(int x)
{
	int ans=0;
	for(;x>0;x-=lowbit(x))
	{
	    ans+=a[x];
	}
	return ans;
}
int main()
{
    cin>>n>>m;
    for(int i=1;i<=m;i++)
    {
    	cin>>k>>l>>r;
    	if(k==1)
    	{
    		change(l);
    		change2(r+1);
    	}
    	else if(k==2)
    	{
    		cout<<ask(r)-ask2(l)<<endl;
    	}
    }
	return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值