I Hate It
原题地址
题目背景
很多学校都有比较的习惯。老师喜欢问,从某某到某某,分数最高的是多少。这让很多学生反感。
题目描述
不管你喜不喜欢,你现在需要做的就是按照老师的要求写一个程序,模拟老师的询问。当然,老师有时需要更新学生的成绩。
输入格式
第一行有两个正整数 n n n 和 m m m( 0 < n ≤ 2 × 1 0 5 , 0 < m < 5000 0<n \le 2\times 10^5,0<m<5000 0<n≤2×105,0<m<5000),分别代表学生人数和操作人数。 ID 编号分别从 1 1 1 编到 n n n。第二行包含 n n n 代表这个的整数 n n n 一个学生的初始成绩,其中第一个 i i i 个数代表 ID 为 i i i 的学生的成绩。接下来有 m m m 行。每一行有一个字符 c c c(只取 Q
或 U
),和两个正整数 a a a, b b b。当 c c c 为 Q
的时候,表示这是一条询问操作,它询问 ID 从 a a a 到 b b b(包括 a , b a,b a,b) 的学生当中,成绩最高的是多少。当 c c c 为 U
的时候,表示这是一条更新操作,如果当前 a a a 学生的成绩低于 b b b,则把 ID 为 a a a 的学生的成绩更改为 b b b,否则不改动。
输出格式
对于每一次询问操作,在一行里面输出最高成绩。
样例 #1
样例输入 #1
5 6
1 2 3 4 5
Q 1 5
U 3 6
Q 3 4
Q 4 5
U 2 9
Q 1 5
样例输出 #1
5
6
5
9
做法
这题和上题一样,也可以用线段树,只用把输入和计算答案的过程稍作修改即可。
#include<bits/stdc++.h>
using namespace std;
int n,m,sum[400010],a[400010];
int p(int x){
sum[x] = max(sum[x*2],sum[x*2+1]);
}
// 初始化函数
void b(int l,int r,int rt){
if(l==r){
sum[rt] = a[l];return ;
}
int mid = l+r>>1;
b(l,mid,rt*2);
b(mid+1,r,rt*2+1);
p(rt);
}
// 修改函数
void xx(int l,int r,int rt,int x,int d){
if(l==r){
sum[rt] = max(sum[rt],d);
return ;
}
int mid = l+r>>1;
if(x<=mid) xx(l,mid,rt*2,x,d);
else xx(mid+1,r,rt*2+1,x,d);
p(rt);
}
// 查询区间
int c(int l,int r,int rt,int x,int y){
if(l>=x and y>=r){
return sum[rt];
}
int mid = l+r>>1;
int ans=0;
if(x<=mid){
ans = max(ans,c(l,mid,rt*2,x,y));
}
if(y>mid){
ans = max(ans,c(mid+1,r,rt*2+1,x,y));
}
return ans;
}
int main(){
cin >> n >> m;
for(int i=1;i<=n;i++){
cin >> a[i];
}
b(1,n,1);
for(int i=1;i<=m;i++){
int x,y;char p;
cin >> p >> x >> y;
if(p=='Q'){
cout << c(1,n,1,x,y) << endl;
}else{
xx(1,n,1,x,y);
}
}
return 0;
}