hdu1540

花式维护。。

维护的是从左端开始的连续长度、从右端开始的连续长度以及总的连续长度

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

const int N = 50050;

int n, m;
int s[N], top;

struct Node{
	int l, r;
	int ls, rs, ms;
}a[N * 4];

void build(int l, int r, int i){
	a[i]. l = l;
	a[i]. r = r;
	a[i]. ls = a[i]. rs = a[i]. ms = r - l + 1;
	if(l != r){
		int m = (l + r) / 2;
		build(l, m, i * 2);
		build(m + 1, r, 2 * i + 1);
	}
}
void update(int i, int t, int x){
	if(a[i]. l == a[i]. r){
		if(x == 1)
			a[i]. ls = a[i]. rs = a[i]. ms = 1;
		else
			a[i]. ls = a[i]. rs = a[i]. ms = 0;
		return ;
	}
	int m = (a[i]. l + a[i]. r) / 2;
	if(t <= m)
		update(2 * i, t, x);
	else
		update(2 * i + 1, t, x);
	a[i]. ls = a[i * 2]. ls;
	a[i]. rs = a[i * 2 + 1]. rs;
	a[i]. ms = max(max(a[i * 2]. ms, a[i * 2 + 1]. ms), a[i * 2]. rs + a[i * 2 + 1]. ls);
	if(a[i * 2]. ls == a[i * 2]. r - a[i * 2]. l + 1)
		a[i]. ls += a[i * 2 + 1]. ls;
	if(a[i * 2 + 1]. rs == a[i * 2 + 1]. r - a[i * 2 + 1]. l + 1)
		a[i]. rs += a[i * 2]. rs;
}
int query(int i, int t){
	if(a[i]. l == a[i]. r || a[i]. ms == 0 || a[i]. ms == a[i]. r - a[i]. l + 1)
		return a[i]. ms;
	int m = (a[i]. l + a[i]. r) / 2;
	if(t <= m){
		if(t >= a[i * 2]. r - a[i * 2]. rs + 1){
			return query(i * 2, t) + query(2 * i + 1, m + 1);
		}
		else
			return query(2 * i, t);
	}
	else{
		if(t <= a[i * 2 + 1]. l + a[i * 2 + 1]. ls - 1)
			return query(2 * i + 1, t) + query(2 * i, m);
		else
			query(2 * i + 1, t);
	}
}

int main(){
	int i, j, x;
	char ch[2];
	while(~ scanf("%d %d", &n, &m)){
		top = 0;
		build(1, n, 1);
		while(m --){
			scanf("%s", ch);
			if(ch[0] == 'D'){
				scanf("%d", &x);
				s[top ++] = x;
				update(1, x, 0);
			}
			else if(ch[0] == 'Q'){
				scanf("%d", &x);
				printf("%d\n", query(1, x));
			} 
			else{
				if(x > 0){
					x = s[-- top];
					update(1, x, 1);
				}
			}
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38759433/article/details/82528243