poj 3264 Balanced Lineup

Balanced Lineup

Time Limit: 5000MS   Memory Limit: 65536K
Total Submissions: 23316   Accepted: 10844
Case 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 3
1
7
3
4
2
5
1 5
4 6
2 2

Sample Output

6
3
0

Source

// 题意: 给出一组数,输出区间最大值与最小值的差值,举例:(1,5): (1,6)
                                                         /\
                                     (1,3)(4,5)
#include <stdio.h>#include <stdlib.h>
#define max(xx,yy) xx>yy?xx:yy
#define min(xx,yy) xx<yy?xx:yy
struct segment
{
  int high,low;
  int l,r;
}table[200000];
int arr[200000],MAX,MIN;
void built( int n,int s,int t)
{
  table[n].l=s,table[n].r=t;
  if(s==t)
  {
 table[n].high=table[n].low=arr[s];
  }
  else
  {
 int mid=(s+t)/2;
 built(2*n,s,mid);
 built(2*n+1,mid+1,t);
 table[n].high=max(table[2*n].high,table[2*n+1].high);
 table[n].low=min(table[2*n].low,table[2*n+1].low);
  }
}
void range( int s,int t,int n)
{
  if(table[n].l==s&&table[n].r==t)
  {
 MAX=max(MAX,table[n].high);
 MIN=min(MIN,table[n].low);
  }
  else
  {
 int mid=(table[n].l+table[n].r)>>1;
 if(s<=mid) range(s,min(mid,t),2*n);
 if(t>mid) range(max(mid+1,s),t,2*n+1);
  }
  return;
}
int main ( )
{
    int n,q,head,end;
    scanf("%d%d",&n,&q);
    for( int i=1;i<=n;i++)
      scanf("%d",arr+i);
    built(1,1,n);
    while(q--)
    {
    scanf("%d%d",&head,&end);
    MAX=0;MIN=10000001;
    range(head,end,1);
    printf("%d\n",MAX-MIN);
 }
 //system("pause");
    return 0;
}
posted @ 2012-07-25 14:33  jiai  Views(172)  Comments(0Edit  收藏  举报