题意:有一个长度为n的序列。然后有两种操作,Q a b是输出区间a b内最长上升子序列的长度。A a b c是把区间a b内全部数字加上c。
题解:用线段树维护区间的最长上升子序列长度,那么一个区间的最长上升子序列有三种可能,从左端点开头的一段,或者中间的一段,或者中间到右端点一段。所以线段树应该要维护liml和limr表示当前区间左端点向右延伸上升长度和右端点向左延伸的上升长度,然后在求当前区间的最长上升子序列长度时,是左子区间的和右子区间的上升子序列长度,以及当前区间的liml和limr的较大值。
假设左子区间右端点小于右子区间左端点。那么还能够是左子区间limr和右子区间的liml的合并。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100005;
struct Tree {
int addv, liml, limr;
int len, lv, rv;
}tree[N << 2];
int n, q, a[N];
char op[5];
void pushup(int k, int left, int right) {
int lenn = right - left + 1;
tree[k].lv = tree[k * 2].lv;
tree[k].rv = tree[k * 2 + 1].rv;
tree[k].liml = tree[k * 2].liml;
tree[k].limr = tree[k * 2 + 1].limr;
tree[k].len = max(tree[k * 2].len, tree[k * 2 + 1].len);
if (tree[k * 2].rv < tree[k * 2 + 1].lv) {
if (tree[k * 2].liml == lenn - (lenn / 2))
tree[k].liml += tree[k * 2 + 1].liml;
if (tree[k * 2 + 1].limr == lenn / 2)
tree[k].limr += tree[k * 2].limr;
tree[k].len = max(tree[k].len, tree[k * 2].limr + tree[k * 2 + 1].liml);
}
tree[k].len = max(tree[k].len, max(tree[k].liml, tree[k].limr));
}
void pushdown(int k) {
if (tree[k].addv) {
tree[k * 2].addv += tree[k].addv;
tree[k * 2 + 1].addv += tree[k].addv;
tree[k * 2].lv += tree[k].addv;
tree[k * 2 + 1].lv += tree[k].addv;
tree[k * 2].rv += tree[k].addv;
tree[k * 2 + 1].rv += tree[k].addv;
tree[k].addv = 0;
}
}
void build(int k, int left, int right) {
tree[k].addv = 0;
if (left == right) {
tree[k].lv = tree[k].rv = a[left];
tree[k].liml = tree[k].limr = tree[k].len = 1;
return;
}
int mid = (left + right) / 2;
build(k * 2, left, mid);
build(k * 2 + 1, mid + 1, right);
pushup(k, left, right);
}
void modify(int k, int left, int right, int l, int r, int x) {
if (l <= left && right <= r) {
tree[k].addv += x;
tree[k].lv += x;
tree[k].rv += x;
return;
}
pushdown(k);
int mid = (left + right) / 2;
if (l <= mid)
modify(k * 2, left, mid, l, r, x);
if (r > mid)
modify(k * 2 + 1, mid + 1, right, l, r, x);
pushup(k, left, right);
}
int query(int k, int left, int right, int l, int r) {
if (l <= left && right <= r)
return tree[k].len;
pushdown(k);
int mid = (left + right) / 2;
if (mid >= r)
return query(k * 2, left, mid, l, r);
if (mid < l)
return query(k * 2 + 1, mid + 1, right, l, r);
int res = max(query(k * 2, left, mid, l, mid), query(k * 2 + 1, mid + 1, right, mid + 1, r));
if (tree[k * 2].rv < tree[k * 2 + 1].lv) {
int temp1 = min(mid - l + 1, tree[k * 2].limr);
int temp2 = min(r - mid, tree[k * 2 + 1].liml);
res = max(res, temp1 + temp2);
}
return res;
}
int main() {
int t, cas = 1;
scanf("%d", &t);
while (t--) {
scanf("%d%d", &n, &q);
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]);
build(1, 1, n);
printf("Case #%d:
", cas++);
int l, r, x;
while (q--) {
scanf("%s", op);
if (op[0] == 'q') {
scanf("%d%d", &l, &r);
printf("%d
", query(1, 1, n, l, r));
}
else {
scanf("%d%d%d", &l, &r, &x);
modify(1, 1, n, l, r, x);
}
}
}
return 0;
}