线段树求区间最值

来源:互联网 发布:免备案域名 编辑:程序博客网 时间:2024/05/16 07:58
    #include<stdio.h>  
    #include<string.h>  
    #include<stdlib.h>  
    const int maxn=200000+10;  
    struct node{  
        int s;  
        int l,r;  
    };  
    struct node tree[maxn*10];  
    int a[maxn];  
    int max(int x,int y){  
        return x>y?x:y;  
    }  
    int create_tree(int h,int x,int y){  
        tree[h].l=x;tree[h].r=y;  
        int mid=(x+y)/2;  
        if(x==y){  
            tree[h].s=a[x];  
            return tree[h].s;  
        }  
        int x1=create_tree(h*2,x,mid);  
        int x2=create_tree(h*2+1,mid+1,y);  
        tree[h].s=max(x1,x2);  
        return tree[h].s;         
    }  
    int dfs(int h,int x,int y){   
        if(y<tree[h].l || x>tree[h].r)  
            return 0;  
        if(x<=tree[h].l && y>=tree[h].r)  
            return tree[h].s;  
        int x1=dfs(2*h,x,y);  
        int x2=dfs(2*h+1,x,y);    
        return max(x1,x2);    
    }  
    int update(int h,int x){      
        if(x<tree[h].l || x>tree[h].r)  
            return tree[h].s;  
        if(tree[h].l==tree[h].r){  
            tree[h].s=a[tree[h].l];  
            return tree[h].s;  
        }  
        int x1=update(2*h,x);  
        int x2=update(2*h+1,x);  
        tree[h].s=max(x1,x2);  
        return tree[h].s;     
    }  
      
    int main(){  
        int i,j,k,m,n;  
        int x,y;  
        char c;  
    while(scanf("%d%d",&n,&m)!=EOF){  
        for(i=1;i<=n;i++)scanf("%d",&a[i]);  
        create_tree(1,1,n);  
        for(i=1;i<=m;i++){  
            getchar();  
            scanf("%c %d %d",&c,&x,&y);  
            if(c=='Q'){  
                printf("%d\n",dfs(1,x,y));  
            }else{   
                a[x]=y;  
                update(1,x);  
            }  
        }  
    }  
        return 0;  
    } 
0 0
原创粉丝点击