hdu 4638 Group 单点修改和离线线段树

跟hdu4630如出一辙,但是思想上还是要有特别技巧

对于[l,r]上的数a[i],我们给一个标记mark[i],表示第第i个数属于某个连续区间

初始时都赋值为0

pos[a[i]] 表示值为a[i]的数所在位置

当遇到情况 a[i]+1 或 a[i]-1 曾经 出现过时,mark[ pos[a[i]-1] ] = 1 或 mark[ pos[a[i]+1] ] = 1

最终结果 = (r-l+1) - sum(mark[l...r]) 

可以用线段树来储存mark[],维护sum

但这种算法的正确性来源于我们从左到右递推,而询问不会从左到右这么巧

所以我们要离线

#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <vector>
#include <set>
#include <queue>
#include <map>
using namespace std;
#define INF 1e9
#define maxn 100010
#define rep(i,x,y) for(int i=x;i<=y;i++)
#define mset(x) memset(x,0,sizeof(x))
const int maxnode = 100010*4;

int x, x1, x2, res;
struct IntervalTree{
	
	int sumv[maxnode];

	void init(){ mset(sumv); }

	void update(int o, int l, int r){
		if(l==r){
			sumv[o]++;
			return ;
		}
		int mid = l+(r-l)/2, lc = 2*o, rc = 2*o+1;
		if(x<=mid)	update(lc, l, mid);
		else	update(rc, mid+1, r); 
		sumv[o] = sumv[lc] + sumv[rc];
	}

	void query(int o, int l, int r){
		if(x1<=l && x2>=r){
			res+=sumv[o];
			return;
		}
		int mid = l+(r-l)/2, lc = 2*o, rc = 2*o+1;
		if(x1<=mid) query(lc, l, mid);
		if(x2>mid)	query(rc, mid+1, r);
	}

}tree;

int t, n, m;
int a[maxn];
struct operate{
	int l, r, id;
	bool operator< (const operate& c)const{
		return r<c.r;
	}
}op[maxn];
int ans[maxn];
int pos[maxn];

int main(){
//	freopen("a.txt","r",stdin);
//	freopen(".out","w",stdout);
	cin>>t;
	while(t--){
		cin>>n>>m;
		rep(i,1,n)	scanf("%d", &a[i]);
		rep(i,1,m){
			scanf("%d%d", &op[i].l, &op[i].r);
			op[i].id = i;
		}

		sort(op+1, op+m+1);
		
		memset(pos, -1, sizeof(pos));
		tree.init();
		int qcnt=1;
		rep(i,1,n){
			if( pos[a[i]-1]>=0 ){
				x = pos[a[i]-1];
				tree.update(1,1,n);
			}
			if( pos[a[i]+1]>=0 ){
				x = pos[a[i]+1];
				tree.update(1,1,n);
			}
			while(qcnt<=m && op[qcnt].r==i){
				x1 = op[qcnt].l, x2 = op[qcnt].r; 
				res = 0;
				tree.query(1,1,n);
				ans[op[qcnt].id] = (x2 - x1 + 1) - res;
				qcnt++;
			}
			if(qcnt>m)	break;
			pos[a[i]] = i;
		}

		rep(i,1,m)	printf("%d\n", ans[i]);
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值