I Hate It
题意:
有多组测试,每个测试第一行給定两个正整数 n、m,代表学生数和操作数,学生ID从 1 到 n 编号;
第二行有 n 个整数,代表这 n 个学生的初始成绩;
接下来 m 行,每行有一个字符 c(只取‘Q’或‘U’),和两个正整数 A, B;
当 c 为‘Q’,表示这是一条询问操作,询问 ID 从 A~B(包括 A、B)的学生中成绩最高的是多少;
当 c 为‘U’,表示这是一条更新操作,要求把 ID 为 A 的学生的成绩更改为 B;
对于每次询问,在一行里输出最高成绩。
数据范围:
0<N<=200000,0<M<5000
解题思路:
线段树
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <set>
using namespace std;
#define INF 0x3f3f3f
#define zero 1e-7
typedef long long ll;
const int N=2e5+5;
int a[N];
struct node {
int l, r, best;//区间,最高成绩
}tree[N<<2];//tree数组存储线段树,节点的编号方法类似于二叉堆
void build(int l, int r, int p) {
tree[p].l=l;//节点p代表区间[l,r]
tree[p].r=r;
if(l==r) {//叶节点
tree[p].best=a[l];
return ;
}
int mid=(l+r)>>1;//折半
build(l, mid, p<<1);//左子节点[l,mid],编号p*2
build(mid+1, r, (p<<1)|1);//右子节点[mid+1,r],编号p*2+1
tree[p].best=max(tree[p<<1].best, tree[(p<<1)|1].best);//自下而上传递信息
}
void update(int l, int r, int p, int id, int nnew) {
if(tree[p].l==tree[p].r) {//找到叶节点
tree[p].best=nnew;
return ;
}
int mid=(l+r)>>1;
if(id<=mid) update(l, mid, p<<1, id, nnew);//x属于左半区间
else update(mid+1, r, (p<<1)|1, id, nnew);//x属于右半区间
tree[p].best=max(tree[p<<1].best, tree[(p<<1)|1].best);//自下而上更新信息
}
int query(int l, int r, int p, int s, int t) {
if(s<=l && r<=t) return tree[p].best;//完全覆盖
int mid=(l+r)>>1;
if(t<=mid) return query(l, mid, p<<1, s, t);
else if(s>mid) return query(mid+1, r, (p<<1)|1, s, t);
else return max(query(l, mid, p<<1, s, t), query(mid+1, r, (p<<1)|1, s, t));
}
int main() {
int n, m, A, B;
char c;
while(scanf("%d %d", &n, &m)!=EOF) {
for(int i=1; i<=n; i++) {
scanf("%d", &a[i]);
}
build(1, n, 1);
while(m--) {
scanf(" %c %d %d", &c, &A, &B);
if(c=='Q') {
printf("%d\n", query(1, n, 1, A, B));//区间,节点,查询区间
}
else {
update(1, n, 1, A, B);//区间,节点,ID,修改值
}
}
}
return 0;
}