其他分享
首页 > 其他分享> > POJ--3264--Balanced Lineup

POJ--3264--Balanced Lineup

作者:互联网

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 ≤ ABN), 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

题目描述:
输入n个数,m次询问,建树,每个节点储存该区间的最大值和最小值,询问则是输出改区间的最大值减最小值

代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define maxn 50005
int map[maxn],n,m;
struct node
{
 int left;
 int right;
 int max;
 int min;
}tree[maxn<<2];
void pushup(int k)
{
 tree[k].max=max(tree[k<<1].max,tree[k<<1|1].max);
 tree[k].min=min(tree[k<<1].min,tree[k<<1|1].min);
}
void build(int l,int r,int k)
{
 tree[k].left=l;
 tree[k].right=r;
 if(l==r)
 {
  tree[k].max=tree[k].min=map[l];
  return;
 }
 int mid=(l+r)/2;
 build(l,mid,k<<1);
 build(mid+1,r,k<<1|1);
 pushup(k);
}
int qureymax(int l,int r,int k)
{
 if(tree[k].left>=l&&tree[k].right<=r)//
 {
  return tree[k].max;
 }
 int mid=(tree[k].left+tree[k].right)/2;
 if(mid>=r)
 {
  return qureymax(l,r,k<<1);
 }
 else if(mid<l)//
 {
  return qureymax(l,r,k<<1|1);
 }
 else
 {
  return max(qureymax(l,mid,k<<1),qureymax(mid+1,r,k<<1|1));
 }
}
int qureymin(int l,int r,int k)
{
 if(tree[k].left>=l&&tree[k].right<=r)//
 {
  return tree[k].min;
 }
 int mid=(tree[k].left+tree[k].right)/2;
 if(mid>=r)
 {
  return qureymin(l,r,k<<1);
 }
 else if(mid<l)//hbukvbyu
 {
  return qureymin(l,r,k<<1|1);
 }
 else
 {
  return min(qureymin(l,mid,k<<1),qureymin(mid+1,r,k<<1|1));
 }
}
int main()
{
 while(scanf("%d%d",&n,&m)!=EOF)
 {
  for(int i=1;i<=n;i++)
  {
   scanf("%d",&map[i]);
  }
  build(1,n,1);
  while(m--)
  {
   int a,b;
   scanf("%d%d",&a,&b);
   printf("%d\n",qureymax(a,b,1)-qureymin(a,b,1));
  }
 }
 return 0;
}

标签:right,return,int,tree,mid,cows,POJ,Balanced,Lineup
来源: https://www.cnblogs.com/tanwei-hq/p/10544224.html