很多学校流行一种比较的习惯。老师们很喜欢询问,从某某到某某当中,分数最高的是多少。
这让很多学生很反感。
不管你喜不喜欢,现在需要你做的是,就是按照老师的要求,写一个程序,模拟老师的询问。当然,老师有时候需要更新某位同学的成绩。
Input
本题目包含多组测试,请处理到文件结束。
在每个测试的第一行,有两个正整数 N 和 M ( 0<N<=200000,0<M<5000 ),分别代表学生的数目和操作的数目。
学生ID编号分别从1编到N。
第二行包含N个整数,代表这N个学生的初始成绩,其中第i个数代表ID为i的学生的成绩。
接下来有M行。每一行有一个字符 C (只取’Q’或’U’) ,和两个正整数A,B。
当C为’Q’的时候,表示这是一条询问操作,它询问ID从A到B(包括A,B)的学生当中,成绩最高的是多少。
当C为’U’的时候,表示这是一条更新操作,要求把ID为A的学生的成绩更改为B。
Output
对于每一次询问操作,在一行里面输出最高成绩。
Sample Input
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
Sample Output
5
6
5
9
Hint
Huge input,the C function scanf() will work better than cin
树状数组做法
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <cctype>
#include <cstdio>
#include <bitset>
#include <string>
#include <vector>
#include <complex>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <algorithm>
using namespace std;
int n,m;
int a[200010],c[200010];
int lowbit(int x)
{
return x&(-x);
}
void change(int x,int d)
{
a[x]=d;
for(int i=x;i<=n;i+=lowbit(i))
{
c[x]=d;
for(int j=1;j<lowbit(i);j<<=1)
c[i]=max(c[i],c[i-j]);
}
}
int ask(int l,int r)
{
int ans=0;
while(1)
{
ans=max(ans,a[r]);
if(l==r)break;
for(r-=1;r-lowbit(r)>=l;r-=lowbit(r))
ans=max(ans,c[r]);
}
return ans;
}
int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(0);
string s;int x,y;
int k;
while(cin>>n>>m)
{
memset(c,0,sizeof(c));
for(int i=1;i<=n;i++)
{
cin>>k;
a[i]=k;c[i]=k;
for(int j=1;j<lowbit(i);j<<=1)
c[i]=max(c[i],c[i-j]);
}
while(m--)
{
cin>>s>>x>>y;
if(s[0]=='U')change(x,y);
else cout<<ask(x,y)<<endl;
}
}
return 0;
}
线段树做法
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <cctype>
#include <cstdio>
#include <bitset>
#include <string>
#include <vector>
#include <complex>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <algorithm>
using namespace std;
int n,m;
int a[200010],tree[800010];
void build(int root,int l,int r)
{
if(l==r){tree[root]=a[l];return;}
int mid=(l+r)>>1;
int lc=root*2;int rc=lc+1;
build(lc,l,mid);
build(rc,mid+1,r);
tree[root]=max(tree[lc],tree[rc]);
}
void change(int p,int x,int l,int r,int root)
{
if(l==r){tree[root]=x;return;}
int mid=(l+r)>>1;
int lc=root*2;int rc=lc+1;
if(p<=mid)change(p,x,l,mid,lc);
else change(p,x,mid+1,r,rc);
tree[root]=max(tree[lc],tree[rc]);
}
int ask(int L,int R,int l,int r,int root)
{
if(L<=l&&r<=R)return tree[root];
int ans=0;
int mid=(l+r)>>1;
int lc=root*2;int rc=lc+1;
if(L<=mid)ans=max(ans,ask(L,R,l,mid,lc));
if(R>mid)ans=max(ans,ask(L,R,mid+1,r,rc));
return ans;
}
int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(0);
string s;
int x,y;
int k;
while(cin>>n>>m)
{
for(int i=1;i<=n;i++)cin>>a[i];
build(1,1,n);
while(m--)
{
cin>>s>>x>>y;
if(s[0]=='U')change(x,y,1,n,1);
else cout<<ask(x,y,1,n,1)<<endl;
}
}
return 0;
}