专题二树形结构 C - Can you answer these queries III
- 题目
You are given a sequence A of N (N <= 50000) integers between -10000 and 10000. On this sequence you have to apply M (M <= 50000) operations:
modify the i-th element in the sequence or for given x y print max{Ai + Ai+1 + .. + Aj | x<=i<=j<=y }.Input
The first line of input contains an integer N. The following line contains N integers, representing the sequence A1..AN.
The third line contains an integer M. The next M lines contain the operations in following form:
0 x y: modify Ax into y (|y|<=10000).
1 x y: print max{Ai + Ai+1 + .. + Aj | x<=i<=j<=y }.Output
For each query, print an integer as the problem required.
Example
Input: 4 1 2 3 4 4 1 1 3 0 3 -3 1 2 4 1 3 3 Output: 6 4 -3
- 思路
A的基础上面加了个单点修改
A题:https://www.cnblogs.com/Benincasa/p/15866592.html - 代码
#include<cstdio> #include<iostream> #include<string> #include<cstring> #include<algorithm> using namespace std; #define clear(a,x) memset(a,x,sizeof(a)) #define ll long long const int M=4e5; struct Node { int lsum, rsum, sum, maxx; }ss[M]; int a[M << 2];//??? //ll sum[M],lsum[M],rsum[M],maxx[M]; int n,q; void up(int p) { ss[p].sum = ss[p << 1].sum + ss[(p << 1) + 1].sum; ss[p].lsum = max(ss[p << 1].lsum, ss[p << 1].sum + ss[p << 1 | 1].lsum); ss[p].rsum = max(ss[p << 1 | 1].rsum, ss[p << 1 | 1].sum + ss[p << 1].rsum); ss[p].maxx = max(max(ss[p << 1].maxx, ss[p << 1 | 1].maxx), ss[p << 1].rsum + ss[p << 1 | 1].lsum); } void build(int s, int t, int p) { if (s == t) { ss[p].lsum = ss[p].rsum = ss[p].maxx = ss[p].sum = a[s]; return; } int m = s + ((t - s) >> 1); build(s, m, p << 1), build(m + 1, t, p << 1 | 1); up(p); } void change(int x, int c, int s, int t, int p) { int m = s + ((t - s) >> 1); if (s == x && s == t) { ss[p].maxx = ss[p].lsum = ss[p].rsum = ss[p].sum = c; return; } if (x <= m) change(x, c, s, m, p << 1); else change(x, c, m+1, t, p << 1 | 1); up(p); } Node query(int l, int r, int s, int t, int p){ if (l <= s && t <= r) return ss[p]; int m = s + ((t - s) >> 1); if (m >= r) return query(l, r, s, m, p << 1) ; else if (m < l) return query(l, r, m + 1, t, p << 1 | 1); else { Node ls = query(l, r, s, m, p << 1); Node rs = query(l, r, m + 1, t, p << 1 | 1); Node ans ; ans.maxx = max(max(ls.maxx, rs.maxx), ls.rsum + rs.lsum); ans.lsum = max(ls.lsum, ls.sum + rs.lsum); ans.rsum = max(rs.rsum, rs.sum + ls.rsum); ans.sum = ls.sum + rs.sum; return ans; } } int main() { scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%d",&a[i]); } build(1,n,1); scanf("%d",&q); int op,x,y; while (q--) { cin >> op >> x >> y; if(op==1) { cout << query(x, y, 1, n, 1).maxx <<endl; } else { change(x, y, 1, n, 1); } } return 0; }