poj 3264 Balanced Lineup(简单线段树)

来源:互联网 发布:易语言访问网页源码 编辑:程序博客网 时间:2024/05/14 15:23

题目大意:输入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;}


                                             
0 0