线段树维护区间最大子段和

感觉线段树白学了,遇到啥不会啥。

对于一个序列,要维护它的区间最大子段和,可以用线段树来做。当然,这是查询比较多的情况,比较少就直接O(n)DP了。

线段树维护4个东西:

1,区间答案,即该区间最大子段和

2,包含左端点的最大子段和

3,包含右端点的最大子段和

4,区间和

1是要维护的答案,2,3,4都是辅助来维护1的

具体操作:

区间答案可以由三种情况推出:qmax(qmax(左儿子的1,右儿子的1), 左儿子的3 + 右儿子的2)

维护2 :qmax(左儿子的2,左儿子的4+右儿子的2)

维护3同理

维护4就是常规操作了

Code:

#define lson i << 1
#define rson i << 1 | 1

struct node{
	int l, r;
	int msum, lsum, rsum, sum;
}tree[maxn<<2];

int n;

void push_up(int i){
	tree[i].msum = qmax(qmax(tree[lson].msum, tree[rson].msum), tree[lson].rsum + tree[rson].lsum);
	tree[i].lsum = qmax(tree[lson].lsum, tree[lson].sum + tree[rson].lsum);
	tree[i].rsum = qmax(tree[rson].rsum, tree[rson].sum + tree[lson].rsum);
	tree[i].sum = tree[lson].sum + tree[rson].sum;
}

void build(int i, int l, int r){
	tree[i].l = l, tree[i].r = r;
	if(l == r) { tree[i].msum = tree[i].lsum = tree[i].rsum = tree[i].sum = 0; return ; }
	int mid = (l + r) >> 1;
	build(lson, l, mid);
	build(rson, mid + 1, r);
	push_up(i);
}

void update(int i, int pos, int val){
	if(tree[i].l == tree[i].r) { tree[i].msum += val;  tree[i].lsum += val; tree[i].rsum += val; tree[i].sum += val; return ; }
	int mid = (tree[i].l + tree[i].r) >> 1;
	if(pos <= mid) update(lson, pos, val);
	else update(rson, pos, val);
	push_up(i);
}

node Query(int i, int l, int r){
	if(tree[i].l >= l && tree[i].r <= r) return tree[i];
	int mid = (tree[i].l + tree[i].r) >> 1;
	if(r <= mid) return Query(lson, l, r);
	else if(l > mid) return Query(rson, l, r);
	else {
		node left = Query(lson, l, mid), right = Query(rson, mid + 1, r);
		node ret;
		ret.sum = left.sum + right.sum;
		ret.msum = qmax(qmax(left.msum, right.msum), left.rsum + right.lsum);
		ret.lsum = qmax(left.lsum, left.sum + right.lsum);
		ret.rsum = qmax(right.rsum, right.sum + left.rsum);
		return ret;
	}
}

int main()
{
	int n; scanf("%d", &n);
	build(1, 1, n);
	rep(i, 1, n){
		int x; scanf("%d", &x);
		update(1, i, x);
	}
	cout << Query(1, 1, n).msum << endl;
	return 0;
}

 

你可能感兴趣的:(线段树)