Vijos 1448校门外的树(线段树)

传送门:https://vijos.org/p/1448

题意:查询一个区间内被修改的次数。

思路:线段树单点更新,区间查询。

利用括号序列的方法,更新区间[a,b]时,点a记录左括号数,点b记录右括号数,查询区间[a,b]时,即为b之前(包括b)的左括号数-a之前的右括号数。

#include <bits/stdc++.h>
using namespace std;

#define lson rt<<1,l,mid
#define rson rt<<1|1,mid+1,r

typedef long long ll;
const int INF=0x3f3f3f3f;
const int maxn=1e5+10;
int T,n,m;
int Left[maxn<<2],Right[maxn<<2];

void Init(){
	memset(Left,0,sizeof(Left));
	memset(Right,0,sizeof(Right));
}

void PushUp(int rt){
	Left[rt]=Left[rt<<1]+Left[rt<<1|1];
	Right[rt]=Right[rt<<1]+Right[rt<<1|1];
}

void Update(int rt,int l,int r,int pos,bool flag){
	if(l==r){
		if(!flag) Left[rt]++;
		else Right[rt]++;
		return ;
	}
	int mid=(l+r)>>1;
	if(pos<=mid) Update(lson,pos,flag);
	else Update(rson,pos,flag);
	PushUp(rt);
}

int Query(int rt,int l,int r,int L,int R,bool flag){
	if(L<=l&&r<=R){
		if(!flag) return Left[rt];
		else return Right[rt];
	}
	int mid=(l+r)>>1;
	int res=0;
	if(L<=mid) res+=Query(lson,L,R,flag);
	if(R>mid) res+=Query(rson,L,R,flag);
	return res;
}

int main() {
#ifndef ONLINE_JUDGE
	freopen("test.in","r",stdin);
	freopen("test.out","w",stdout);
#endif
	while(~scanf("%d%d",&n,&m)){
		Init();
		int op,a,b;
		while(m--){
			scanf("%d%d%d",&op,&a,&b);
			if(op==1) {
				Update(1,1,n,a,false);
				Update(1,1,n,b,true);
			}
			else {
				int l,r;
				l=Query(1,1,n,1,b,false);
				if(a==1) r=0;
				else r=Query(1,1,n,1,a-1,true);
				printf("%d\n",l-r);
			}
		}
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值