Balanced Lineup
Time Limit: 5000MS | | Memory Limit: 65536K |
Total Submissions: 50919 | | Accepted: 23849 |
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
题目链接: http://poj.org/problem?id=3264
题目大意: 给出初始化的区间值,m次查询
每次查询区间[a,b]的最大值-最小值
解题思路: 线段树 更新: 无更新 查询:区间查询
建立线段树的时候,每个结点存储左右子树的最大值和最小值
查询时直接访问区间最大值和最小值,不需要查找到最低
查询时间复杂度O(logN)
代码:
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define MAXN 70000
- #define INF 0x3f3f3f3f
- #define MAX(a,b) a>b?a:b
- #define MIN(a,b) a<b?a:b
- #define MID(a,b) (a+b)>>1
- #define L(a) a<<1
- #define R(a) (a<<1)+1
-
- typedef struct snode{
- int left,right;
- int max,min;
- }Node;
-
- Node Tree[MAXN<<1];
- int num[MAXN],minx,maxx;
-
- void Build(int t,int l,int r)
- {
- int mid;
- Tree[t].left=l,Tree[t].right=r;
- if(Tree[t].left==Tree[t].right)
- {
- Tree[t].max=Tree[t].min=num[l];
- return ;
- }
- mid=MID(Tree[t].left,Tree[t].right);
- Build(L(t),l,mid);
- Build(R(t),mid+1,r);
- Tree[t].max=MAX(Tree[L(t)].max,Tree[R(t)].max);
- Tree[t].min=MIN(Tree[L(t)].min,Tree[R(t)].min);
- }
-
- void Query(int t,int l,int r)
- {
- int mid;
- if(Tree[t].left==l&&Tree[t].right==r)
- {
- if(maxx<Tree[t].max)
- maxx=Tree[t].max;
- if(minx>Tree[t].min)
- minx=Tree[t].min;
- return ;
- }
- mid=MID(Tree[t].left,Tree[t].right);
- if(l>mid)
- {
- Query(R(t),l,r);
- }
- else if(r<=mid)
- {
- Query(L(t),l,r);
- }
- else
- {
- Query(L(t),l,mid);
- Query(R(t),mid+1,r);
- }
- }
-
- int main()
- {
- int n,m,a,b,i;
- memset(Tree,0,sizeof(Tree));
- scanf("%d%d",&n,&m);
- for(i=1;i<=n;i++)
- scanf("%d",&num[i]);
- Build(1,1,n);
- while(m--)
- {
- scanf("%d%d",&a,&b);
- maxx=0;minx=INF;
- Query(1,a,b);
- printf("%d\n",maxx-minx);
- }
- return 0;
- }