poj3264 线段树求最大值,最小值

#include <iostream>
#include<stdio.h>
using namespace std;
const int maxn=50000+5;
int n,q;
int height[maxn];
struct segtree
{
    int left,right;
    int maxx,minn;
};
segtree tree[maxn*4];

void build(int low,int high,int index)
{
    tree[index].left=low;
    tree[index].right=high;
    if(low==high)
    {
        tree[index].maxx=height[low];
        tree[index].minn=height[low];
        return;
    }
    else
    {
        int mid=(low+high)/2;
        build(low,mid,index*2);
        build(mid+1,high,index*2+1);
        tree[index].maxx=max(tree[index*2].maxx,tree[index*2+1].maxx);
        tree[index].minn=min(tree[index*2].minn,tree[index*2+1].minn);
    }
}

int qmax(int low,int high,int index)
{
  if(tree[index].left==low&&tree[index].right==high)
  {
      return tree[index].maxx;
  }
  else
  {
      int mid=(tree[index].left+tree[index].right)/2;
      if(high<=mid)
      {
          return qmax(low,high,index*2);
      }
      else if(low>mid)
      {
          return qmax(low,high,index*2+1);
      }
      else
      {
          return max(qmax(low,mid,index*2),qmax(mid+1,high,index*2+1));
      }
  }
}

int qmin(int low,int high,int index)
{
    if(tree[index].left==low&&tree[index].right==high)
  {
      return tree[index].minn;
  }
  else
  {
      int mid=(tree[index].left+tree[index].right)/2;
      if(high<=mid)
      {
          return qmin(low,high,index*2);
      }
      else if(low>mid)
      {
          return qmin(low,high,index*2+1);
      }
      else
      {
          return min(qmin(low,mid,index*2),qmin(mid+1,high,index*2+1));
      }
  }
}

int main()
{
   scanf("%d%d",&n,&q);
   for(int i=1;i<=n;i++)
    scanf("%d",&height[i]);
   build(1,n,1);
   while(q--)
   {
       int a,b;
       scanf("%d%d",&a,&b);
       printf("%d\n",qmax(a,b,1)-qmin(a,b,1));
   }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值