hdu 1754(线段树)

一道比较简单的线段树,但是还是wa了两遍才ac,线段树写得还是不够熟练。

线段树的模板型挺强的,感觉不容易出现什么bug,就算出现了也都是笔误之类的。

#include<stdio.h>
#include<string.h>
#define N 200005
struct node
{
    int x,y,max;
}a[N*3];
int Max(int x,int y)
{
    return x>y?x:y;
}
void CreatTree(int t,int x,int y)
{
    a[t].x=x;
    a[t].y=y;
    a[t].max=0;
    if(x==y)
        return ;
    int temp=t*2;
    int mid=(x+y)/2;
    CreatTree(temp,x,mid);
    CreatTree(temp+1,mid+1,y);
    return ;
}
void InsertTree(int t,int x,int y)
{
    if(a[t].x==a[t].y&&a[t].x==x)
    {
        a[t].max=y;
        return ;
    }
    int temp=t*2;
    int mid=(a[t].x+a[t].y)/2;
    if(x<=mid)
    {
        InsertTree(temp,x,y);
    }
    else
    {
        InsertTree(temp+1,x,y);
    }
    a[t].max=Max(a[temp].max,a[temp+1].max);
    return ;
}
int FindTree(int t,int x,int y)
{
    int max;
    if(a[t].x==x&&a[t].y==y)
    {
        return a[t].max;
    }
    int temp=t*2;
    int mid=(a[t].x+a[t].y)/2;
    if(y<=mid)
    {
        max=FindTree(temp,x,y);
    }
    else if(x>mid)
    {
        max=FindTree(temp+1,x,y);
    }
    else
    {
        max=Max(FindTree(temp,x,mid),FindTree(temp+1,mid+1,y));
    }
    return max;
}
int main()
{
    int n,m;
    int i;
    char c;
    int temp;
    int x;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        CreatTree(1,1,n);
        for(i=0;i<n;i++)
        {
            scanf("%d",&temp);
            InsertTree(1,i+1,temp);
        }
        while(m--)
        {
            getchar();
            scanf("%c %d %d",&c,&x,&temp);
            if(c=='U')
            {
                InsertTree(1,x,temp);
            }
            else if(c=='Q')
            {
                printf("%d\n",FindTree(1,x,temp));
            }

        }
    }
    return 0;
}


原文地址:https://www.cnblogs.com/javawebsoa/p/3078539.html