void-man

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

给出n个牛的高度,然后询问所给区间内牛的最大高度差是多少?

这题比较简单一点是不用更新,每次只是询问,那么可以直接用两个变量mmax,mmin来保存查找过程中的最大与最小高度值,两个差即可

#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
#include <climits>
#define L(x) (x << 1)
#define R(x) (x << 1 | 1)

using namespace std;

const int MAX = 50010;
struct Tnode{ int mmax,mmin,val; int l,r;};
Tnode node[MAX*3];
int v[MAX],big,small;
void init()
{
	memset(node,0,sizeof(node));
}
void build(int t,int l,int r)
{
	node[t].l = l;
	node[t].r = r;
	if(l==r-1)
	{
	    node[t].mmin=v[l];
	    node[t].mmax=v[l];
	    //node[t].val = v[l];
	return ;
	}
	int mid = ( l + r ) >> 1;
	build(L(t), l, mid);
	build(R(t), mid, r);
	node[t].mmax=max(node[L(t)].mmax,node[R(t)].mmax);
	node[t].mmin=min(node[L(t)].mmin,node[R(t)].mmin);
}


void get(int t,int l,int r)
{
	if( node[t].l == l && node[t].r ==r )
	{
		big=max(node[t].mmax,big);
		small=min(node[t].mmin,small);
		return ;
	}
	int mid = (node[t].l + node[t].r) >> 1;
	if( l >= mid )
		 get(R(t),l,r);
    else if( r <= mid )
         get(L(t),l,r);
        else
        {
           get(R(t),mid,r);
           get(L(t),l,mid);
        }
}

int main()
{
    int n,m,x,y;
    while( ~scanf("%d%d",&n,&m) )
    {
        init();
        for(int i=1; i<=n; i++)
            scanf("%d",&v[i]);
        build(1,1,n+1);
        while( m-- )
        {
            scanf("%d%d",&x,&y);
            small = INT_MAX; big = 0;
            get(1,x,y+1);
            printf("%d\n",big - small);
        }
    }

return 0;
}

posted on 2011-08-06 23:41  void-man  阅读(157)  评论(0)    收藏  举报