poj 3264 Balanced Lineup(簡單線段樹)

題目大意:輸入N個數和Q個查詢,每次查詢區間[L,D]中的最大數和最小數的差。
題解:用線段樹記錄區間的最大值和最小值,輸出相減的結果即可。


#include <iostream>
#include <stdio.h>

using namespace std;

struct node{
    int l,r;
    int minN,maxN;
};

node tree[200005];
int n,q,a[50005],l,r,maxN,minN;

void buildTree(int root,int l,int r){//建樹
    tree[root].l = l;
    tree[root].r = r;
    if(l == r){
        tree[root].minN = a[l];
        tree[root].maxN = a[l];
        return;
    }
    buildTree(2*root,l,(l+r)/2);
    buildTree(2*root+1,(l+r)/2+1,r);
    tree[root].minN = min(tree[2*root].minN,tree[2*root+1].minN);
    tree[root].maxN = max(tree[2*root].maxN,tree[2*root+1].maxN);
}

void query(int root,int l,int r){//查詢區間l,r的最大值、最小值,將值存在全局變量
    if(tree[root].l == l && tree[root].r == r){
        minN = min(minN,tree[root].minN);
        maxN = max(maxN,tree[root].maxN);
        return;
    }
    int mid = (tree[root].l+tree[root].r)/2;
    if(r <= mid){
        query(2*root,l,r);
    }
    else if(l > mid){
        query(2*root+1,l,r);
    }
    else{
        query(2*root,l,mid);
        query(2*root+1,mid+1,r);
    }
}

int main()
{
    scanf("%d%d",&n,&q);
    for(int i = 1; i <= n; i ++){
        scanf("%d",&a[i]);
    }
    buildTree(1,1,n);
    for(int i = 0; i < q; i ++){
        scanf("%d%d",&l,&r);
        maxN = 0;
        minN = 10000000;
        query(1,l,r);
        printf("%d\n",maxN - minN);
    }
    return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章