poj 3264

poj 3264

初识线段树
WA了很多次,在改了很多次之后 发现是我数组开小了,😭
先建树,然后通过取中值,“精准”的把要的那一片树遍历一下。
然后自己还错在 一开始中值取的l+r>>1 应该是要取t[n].l+t[n].r>>1;
然后在这里也WA了很多次,被自己蠢哭

//初识线段树  poj3264
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
#define maxx 1000010
int maxxx,minnn,a[maxx];
struct tree{
    int l,r;
    int s;
    int ma,mi;
}t[maxx<<2];
void build(int l,int r,int n)
{
    t[n].l=l;
    t[n].r=r;
    t[n].ma=0;
    t[n].mi=maxx;
    if(l==r)
    {
        t[n].ma=t[n].mi=a[l];
        return;
    }
    int mid=(l+r)>>1;
    build(l,mid,n<<1);
    build(mid+1,r,n<<1|1);
    t[n].s=t[n<<1].s+t[n<<1|1].s;
    t[n].ma=max(t[n<<1].ma,t[n<<1|1].ma);
    t[n].mi=min(t[n<<1].mi,t[n<<1|1].mi);
}
void check(int l,int r,int n)
{
    if(t[n].l==l&&t[n].r==r)
    {
        maxxx=max(maxxx,t[n].ma);
        minnn=min(minnn,t[n].mi);
        return;
    }
    int mid =(t[n].l+t[n].r)>>1;
    if(r<=mid)
    {
        check(l,r,n<<1);
    }
    else if(l>mid)
    {
        check(l,r,n<<1|1);
    }
    else
    {
        check(l,mid,n<<1);
        check(mid+1,r,n<<1|1);
    }
}
int main()
{
    int n,m;
    int check1,check2;
    while(~scanf("%d",&n))
    {
        scanf("%d",&m);
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
        }
        build(1,n,1);
        while(m--) {
            minnn=maxx;
            maxxx=0;
            scanf("%d%d", &check1, &check2);
            check(check1, check2, 1);
            printf("%d\n",maxxx-minnn);
        }
    }
    return 0;
}
posted @ 2019-03-19 19:28  丶斗北  阅读(105)  评论(0)    收藏  举报