线段树
和BZOJ那道楼房重建有点像,用线段树维护两个值:可以摘的苹果和区间最大值。
每次pushup的时候左子树是肯定能够算的,剩下的算右子树就好了。
右子树的最大值如果小于左子树,那么贡献是0。
否则,看右子树的左子树,如果右子树的左子树最大值小于原左子树,那么答案一定在右子树的右子树,递归寻找即可。
如果右子树的左子树最大值大于原左子树,那么当前这个区间(也就是右子树这整个区间)减去当前这个区间的左子树的答案就是右子树的贡献,是一定存在的,因为原区间的左子树对它没有影响,剩下的递归右子树的左子树寻找答案就好了。#include#define INF 0x3f3f3f3f#define full(a, b) memset(a, b, sizeof a)#define FAST_IO ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)using namespace std;typedef long long ll;inline int lowbit(int x){ return x & (-x); }inline int read(){ int X = 0, w = 0; char ch = 0; while(!isdigit(ch)) { w |= ch == '-'; ch = getchar(); } while(isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar(); return w ? -X : X;}inline int gcd(int a, int b){ return b ? gcd(b, a % b) : a; }inline int lcm(int a, int b){ return a / gcd(a, b) * b; }template inline T max(T x, T y, T z){ return max(max(x, y), z); }template inline T min(T x, T y, T z){ return min(min(x, y), z); }template inline A fpow(A x, B p, C lyd){ A ans = 1; for(; p; p >>= 1, x = 1LL * x * x % lyd)if(p & 1)ans = 1LL * x * ans % lyd; return ans;}const int N = 200005;int _, n, m, a[N], tree[N<<2], maxi[N<<2];int query(int rt, int l, int r, int val){ if(l == r) return maxi[rt] > val; if(maxi[rt] <= val) return 0; int mid = (l + r) >> 1; if(maxi[rt << 1] <= val) return query(rt << 1 | 1, mid + 1, r, val); else return tree[rt] - tree[rt << 1] + query(rt << 1, l, mid, val);}void push_up(int rt, int l, int r){ int mid = (l + r) >> 1; maxi[rt] = max(maxi[rt << 1], maxi[rt << 1 | 1]); tree[rt] = tree[rt << 1] + query(rt << 1 | 1, mid + 1, r, maxi[rt << 1]);}void buildTree(int rt, int l, int r){ if(l == r){ tree[rt] = 1, maxi[rt] = a[l]; return; } int mid = (l + r) >> 1; buildTree(rt << 1, l, mid); buildTree(rt << 1 | 1, mid + 1, r); push_up(rt, l, r);}void modify(int rt, int l, int r, int pos, int k){ if(l == r){ maxi[rt] = k; return; } int mid = (l + r) >> 1; if(pos <= mid) modify(rt << 1, l, mid, pos, k); else modify(rt << 1 | 1, mid + 1, r, pos, k); push_up(rt, l, r);}int main(){ for(_ = read(); _; _ --){ n = read(), m = read(); for(int i = 1; i <= n; i ++) a[i] = read(); buildTree(1, 1, n); while(m --){ int pos = read(), k = read(), temp = a[pos]; modify(1, 1, n, pos, k); printf("%d\n", tree[1]); modify(1, 1, n, pos, temp); } } return 0;}