題目連接
題意:
求區間內最大值
N個人 1 ~ N
M 次查詢 + 修改
當C爲'Q' 詢問操作,它詢問ID從A到B(包括A,B)的學生當中,成績最高的是多少。
當C爲'U' 更新操作,要求把ID爲A的學生的成績更改爲B。
數據範圍:
1s
N 2e5
M 5e3
思路:
求區間內最大值 且 中間有單點修改
1)線段樹
AC:
#include<iostream>
#include<math.h>
#include<algorithm>
#include<stdio.h>
using namespace std;
const int MAX_LEN = 2e5;
int N, M;
int arr[MAX_LEN + 20];
int seg_tree[MAX_LEN << 2];
int lazy[MAX_LEN << 2];
void push_up(int root) {
seg_tree[root] = max(seg_tree[root << 1 ] , seg_tree[root << 1 | 1]);
}
void push_down(int root, int L, int R) {
if(lazy[root]) {
int mid = (L + R) >> 1;
lazy[root << 1] += lazy[root];
lazy[root << 1 | 1] += lazy[root];
seg_tree[root << 1] += lazy[root] * (mid - L + 1); //左子樹上的和加上lazy值
seg_tree[root << 1 | 1] += lazy[root] * (R - mid); //右子樹上的和+上lazy值
lazy[root] = 0;
}
}
void build (int root, int L, int R) {
if (L == R) {
seg_tree[root] = arr[L];
return ;
}
int mid = (L + R) / 2;
// [ L, mid] 左子樹, [mid + 1, r]右子樹
build(root << 1, L, mid);
build(root << 1 | 1, mid + 1, R);
push_up(root);
//對與當前的根節點,把當前的根節點的左右子樹都算出來後,再更新它的值
// 沿路回溯, 回溯到點root 時, 都是被 [ L, R] 或者其子區間影響到的點,邊回溯邊更新
}
//點修改
void update (int root, int L, int R, int pos, int val) {
if(L == R) {
seg_tree[root] = val;
return ;
}
int mid = (L + R) / 2;
// 左區間
if (pos <= mid) update (root << 1, L, mid, pos, val);
//右區間
else update (root << 1 | 1, mid + 1, R, pos, val);
push_up(root);
}
//區間查旬
int query (int root, int L, int R,int LL ,int RR) {
if( L >= LL && R <= RR) {
return seg_tree[root];
}
push_down(root, L, R); //每次訪問都去檢查Lazy標記
int Ans = 0;
int mid = (L + R) >> 1;
if(LL <= mid) Ans = max(Ans, query(root << 1, L, mid, LL, RR));
if(RR > mid) Ans = max(Ans, query(root << 1|1, mid + 1, R, LL, RR));
return Ans;
}
//區間修改
//void update (int root, int L, int R, int LL, int RR, int val) {
// //[LL, RR] 爲即將要更新的區間
// if(LL <= L && R <= RR) {
// lazy[root] += val;
// seg_tree[root] += val * (R - L + 1);
// }
// //更新子樹
// push_down(root, L, R);
// int mid = (L + R) >> 1;
// if(LL <= mid) update(root << 1, L, mid, LL, RR, val);
// if(RR > mid) update(root << 1 | 1, mid + 1, R, LL, RR, val);
// //更新父節點
// push_up(root);
//}
int main(){
//freopen("in.txt", "r", stdin);
while (scanf("%d%d", &N, &M) != EOF) {
for(int i = 1; i <= N; ++i) scanf("%d", &arr[i]);
build(1, 1, N);
char ch[20];
int L, R;
for(int i = 1; i <= M; ++i) {
scanf("%s", ch);
if (ch[0] == 'Q') {
scanf("%d%d", &L, &R);
int Ans = query(1, 1, N, L, R);
printf("%d\n", Ans);
} else {
scanf("%d%d", &L, &R);
update(1, 1, N, L, R);
}
}
}
return 0;
}