G - Balanced Lineup
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.
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.
6 3 1 7 3 4 2 5 1 5 4 6 2 2Sample Output
6 3 0
题意:计算 区间内 最大数 和 最小数 的 差值
思路:维护 区间内 的最大值和最小值 , 之后 查询时 找出最大最小值 , 在计算差值
#include <cstdio> #include <iostream> #include <cstring> #include <algorithm> #include <limits> using namespace std ; #define maxn 60000 int n , q ; int a , b ; int num[maxn] ; int max_ans , min_ans ; struct node { int l , r , max_num , min_num ; }; node tree[maxn*4] ; void build(int root , int l , int r ) { tree[root].l = l ; tree[root].r = r ; if( l == r ){ tree[root].max_num = tree[root].min_num = num[l] ; return; } int mid = (l+r)/2 ; build(root*2 , l , mid ) ; build(root*2+1 , mid+1 , r ) ; tree[root].max_num = max(tree[root*2].max_num , tree[root*2+1].max_num); tree[root].min_num = min(tree[root*2].min_num , tree[root*2+1].min_num); } void query(int root , int s , int e ){ if(e < tree[root].l || tree[root].r < s){ return; } if(s <= tree[root].l && tree[root].r <= e){ max_ans = max(max_ans , tree[root].max_num) ; min_ans = min(min_ans , tree[root].min_num) ; return; } query(root*2 , s , e ) ; query(root*2+1 , s , e ) ; } int main(){ while(~scanf("%d %d" , &n , &q)){ for(int i=1 ; i<=n ; i++){ scanf("%d" , &num[i]) ; } build(1 , 1 , n ) ; for(int i=1 ; i<=q ; i++){ min_ans = INT_MAX , max_ans = INT_MIN ; scanf("%d %d" , &a , &b) ; query(1 , a , b ) ; printf("%d\n" , max_ans - min_ans ) ; } } return 0 ; }