【POJ3264】Balanced Lineup

来源:互联网 发布:html是不是编程语言 编辑:程序博客网 时间:2024/06/06 12:37

Balanced Lineup
Time Limit: 5000MS Memory Limit: 65536KTotal Submissions: 47142 Accepted: 22121Case Time Limit: 2000MS

Description

For the daily milking, Farmer John's N cows (1 ≤ N ≤ 50,000) always line up in the same order. One day Farmer John decides to organize a game of Ultimate Frisbee with some of the cows. To keep things simple, he will take a contiguous range of cows from the milking lineup to play the game. However, for all the cows to have fun they should not differ too much in height.

Farmer John has made a list of Q (1 ≤ Q ≤ 200,000) potential groups of cows and their heights (1 ≤ height ≤ 1,000,000). For each group, he wants your help to determine the difference in height between the shortest and the tallest cow in the group.

Input

Line 1: Two space-separated integers, N and Q
Lines 2..N+1: Line i+1 contains a single integer that is the height of cow i 
Lines N+2..N+Q+1: Two integers A and B (1 ≤ A ≤ B ≤ N), representing the range of cows from A to B inclusive.

Output

Lines 1..Q: Each line contains a single integer that is a response to a reply and indicates the difference in height between the tallest and shortest cow in the range.

Sample Input

6 31734251 54 62 2

Sample Output

630

Source

USACO 2007 January Silver

虽是线段树的模板题,也够我这菜鸟想一天的了(真想了一天快哭了,还没搞太明白大哭),最好先看一看别人对线段树的讲解再看,不然实在是看不懂,数据结构真奇妙,奇妙到我什么都不知道快哭了
#include <iostream>  using namespace std;  #define MAXV 50100  #define MAXT 1<<18  #define max(a,b) a>b?a:b  #define min(a,b) a>b?b:a  int a[MAXV],TL[MAXT],TR[MAXT],TMAX[MAXT],TMIN[MAXT];  //TL与TR代表结点v区间的左边与右边的数,这样方便查询  //TMAX,TMIN,代表结点v的最大值与最小值    void createTree(int v,int f,int t){      TL[v]=f;      TR[v]=t;      if(f==t){          TMAX[v]=a[f];          TMIN[v]=a[f];          return;      }        int mid=(f+t)>>1;      createTree(v<<1,f,mid);      createTree((v<<1)|1,mid+1,t);        TMAX[v]=max(TMAX[v<<1],TMAX[(v<<1)|1]); //这里递归回溯对TMAX(到各个点的最大的值)以及TMIN数组赋值    TMIN[v]=min(TMIN[v<<1],TMIN[(v<<1)|1]);  }  int queryTree(int v,int L,int R,int flag){      if(L==TL[v] && R==TR[v]){          return (flag?TMIN[v]:TMAX[v]);      }        int mid=(TL[v]+TR[v])>>1;                 //这里对是否在L-R区间内的判断有两种方法,一种是这种,还有一种是对序列的下标进行操作    if(R<=mid)                //先v=v<<1;   再v=v+1;        return queryTree(v<<1,L,R,flag);      else if(L>mid)          return queryTree((v<<1)|1,L,R,flag);      else{          if(flag) return min(queryTree(v<<1,L,mid,flag),queryTree((v<<1)|1,mid+1,R,flag));          else return max(queryTree(v<<1,L,mid,flag),queryTree((v<<1)|1,mid+1,R,flag));      }  }    int main(){      int N,Q,L,R,i;      while(scanf("%d%d",&N,&Q)!=EOF){          for(i=1;i<=N;i++)              scanf("%d",&a[i]);            createTree(1,1,N);          while(Q--){              scanf("%d%d",&L,&R);              printf("%d\n",queryTree(1,L,R,0)-queryTree(1,L,R,1));          }      }      return 0;  }  

题目地址:http://poj.org/problem?id=3264





0 0