校门外的树
描述
校门外有很多树,有苹果树,香蕉树,有会扔石头的,有可以吃掉补充体力的……
如今学校决定在某个时刻在某一段种上一种树,保证任一时刻不会出现两段相同种类的树,现有两个操作:
K=1,K=1,读入l、r表示在区间[l,r]中种上一种树,每次操作种的树的种类都不同
K=2,读入l,r表示询问l~r之间能见到多少种树
(l,r>0)
格式
输入格式
第一行n,m表示道路总长为n,共有m个操作
接下来m行为m个操作
输出格式
对于每个k=2输出一个答案
样例1
样例输入1
5 4
1 1 3
2 2 5
1 2 4
2 3 5
样例输出1
1
2
限制
1s
提示
范围:20%的数据保证,n,m<=100
60%的数据保证,n <=1000,m<=50000
100%的数据保证,n,m<=50000
解析:
一道挺有意思的题。对于每个区间(L , R),我们可以理解为在 L 处加入一个 '(' ,在 R 处加入一个 ')' ,答案就为 R 之前的 ‘(’ 的数量减去 L-1 之前的 ‘)’ 的数量,用树状数组可以轻松解决。
代码:
#include <bits/stdc++.h>
using namespace std;
const int Max=50010;
int n,m;
int sum1[Max],sum2[Max];
inline int get_int()
{
int x=0,f=1;
char c;
for(c=getchar();(!isdigit(c))&&(c!='-');c=getchar());
if(c=='-') {f=-1;c=getchar();}
for(;isdigit(c);c=getchar()) x=(x<<3)+(x<<1)+c-'0';
return x*f;
}
inline int lowbit(int x){return x&-x;}
inline void add1(int pos,int x){for(;pos<=n;pos+=lowbit(pos)) sum1[pos]+=x;}
inline void add2(int pos,int x){for(;pos<=n;pos+=lowbit(pos)) sum2[pos]+=x;}
inline int Q1(int pos)
{
int ans=0;
for(;pos;pos-=lowbit(pos)) ans+=sum1[pos];
return ans;
}
inline int Q2(int pos)
{
int ans=0;
for(;pos;pos-=lowbit(pos)) ans+=sum2[pos];
return ans;
}
int main()
{
n=get_int(),m=get_int();
for(int i=1;i<=m;i++)
{
int flag=get_int(),l=get_int(),r=get_int();
if(flag == 1) add1(l,1),add2(r,1);
else cout<<Q1(r) - Q2(l-1)<<"\n";
}
return 0;
}