请自行搜索
题目大意:维护n个位置,支持新建一段区间,查询某一段区间与已加入的多少区间有交。
题解:
神题啊
假设询问区间为[s,t],那么区间[a,b]与[s,t]相交,必要条件是a<=t,但是a<=t的区间不一定与[s,t]相交,也就是b<s的部分,把这部分减去即可。
因此维护两个bit分别维护左右端点,每次询问[s,t]那么答案就是query_in_left(t)-query_in_right(s-1)
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#define MAXN 50010
#define lowbit(x) ((x)&(-(x)))
using namespace std;
int n,m,b1[MAXN],b2[MAXN];
int update(int *b,int x,int v)
{
for(x;x<=n;x+=lowbit(x))
b[x]+=v;
return 0;
}
int query(int *b,int x)
{
int ans=0;
for(x;x;x-=lowbit(x))
ans+=b[x];
return ans;
}
int main()
{
scanf("%d%d",&n,&m);
while(m--)
{
int opt,u,v;scanf("%d%d%d",&opt,&u,&v);
if(opt==1) update(b1,u,1),update(b2,v,1);
else printf("%d\n",query(b1,v)-query(b2,u-1));
}
return 0;
}