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
5 6 5 9HintHuge input,the C function scanf() will work better than cin
看到那么多的查找次数用线段树无疑了。。
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
struct node
{
int left,right,val;
}c[200000*3];
void build_tree(int l,int r,int root)//建树
{
c[root].left=l;
c[root].right=r;
if(l==r)
{
scanf("%d",&c[root].val);
return ;
}
int mid=(c[root].left+c[root].right)/2;
build_tree(l,mid,root*2);
build_tree(mid+1,r,root*2+1);
c[root].val=max(c[root*2].val,c[root*2+1].val);
}
void search_tree(int l,int r,int root,int &Max)//查找
{
if(c[root].left==l&&c[root].right==r)
{
Max=c[root].val;
return ;
}
int mid=(c[root].left+c[root].right)/2;
if(mid<l)
search_tree(l,r,root*2+1,Max);
else if(mid>=r)
search_tree(l,r,root*2,Max);
else
{
int Max1;
search_tree(l,mid,root*2,Max);
search_tree(mid+1,r,root*2+1,Max1);
Max=max(Max,Max1);
}
}
void update_tree(int pos,int root,int x)//更新点
{
if(c[root].left==c[root].right&&c[root].left==pos)
{
c[root].val=x;
return ;
}
int mid=(c[root].left+c[root].right)/2;
if(mid<pos)
update_tree(pos,root*2+1,x);
else
update_tree(pos,root*2,x);
c[root].val=max(c[root*2].val,c[root*2+1].val);
}
int main()
{
int n,m;
while(scanf("%d %d",&n,&m)!=EOF)
{
memset(&c,0,sizeof(&c));
build_tree(1,n,1);
getchar();
for(int i=0;i<m;i++)
{
char ch;
scanf("%c",&ch);
if(ch=='Q')
{
int a,b,Max;
scanf("%d %d",&a,&b);
getchar();
if(a<b)
search_tree(a,b,1,Max);
else
search_tree(b,a,1,Max);
printf("%d\n",Max);
}
if(ch=='U')
{
int a,b;
scanf("%d %d",&a,&b);
getchar();
update_tree(a,1,b);
}
}
}
return 0;
}版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/su20145104009/article/details/47446413