POJ3264

    xiaoxiao2021-03-25  77

    Balanced Lineup Time Limit: 5000MS Memory Limit: 65536KTotal Submissions: 51339 Accepted: 24072Case 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

    大致题意:

    给出n个数,多次查询 第1 到 第m 区间上最大值和最小值的差。

    大体思路:

    线段树 维护区间上最大值和最小值

    #include<cstdio> #include<utility> #define _max 50000+10 #define max(x,y) x>y?x:y #define min(x,y) x<y?x:y int M , N ; int A [_max] ; std::pair<int,int> Seg [4*_max] ; void Build_tree ( int p , int l , int r ) { if ( l==r ){ Seg[p].first = A[l]; Seg[p].second = A[l]; return ; } int mid = ( l + r ) >> 1 ; Build_tree ( 2*p , l , mid ) ; Build_tree (2*p+1 , mid+1 , r ) ; Seg[p].first = max ( Seg[2*p].first , Seg[2*p+1].first ) ; Seg[p].second = min ( Seg[2*p].second , Seg[2*p+1].second ) ; } std::pair<int,int> Query ( int p , int l , int r , int x , int y ) { if ( l>=x && r<=y ) return Seg[p] ; int mid = ( l + r ) >> 1 ; if ( y<=mid ) return Query ( 2*p , l , mid , x , y ) ; if ( x> mid ) return Query (2*p+1 , mid+1 , r , x , y ) ; std::pair<int,int> a , b , t ; a = Query ( 2*p , l , mid , x , y ) ; b = Query (2*p+1 , mid+1 , r , x , y ) ; t.first = max ( a.first , b.first ) ; t.second = min (a.second , b.second ) ; return t ; } int main () { //freopen ( "in.txt" , "r" , stdin ) ; scanf ( "%d%d" , &N , &M ) ; for ( int i=1 ; i<=N ; i++ ) scanf ( "%d" , A+i ) ; Build_tree ( 1 , 1 , N ) ; int x , y ; std::pair<int,int> t ; for( int i=0 ; i<M ; i++ ){ scanf ( "%d%d" , &x , &y ) ; t = Query ( 1 , 1 , N , x , y ) ; printf ( "%d\n" , t.first-t.second ) ; } return 0 ; }

    转载请注明原文地址: https://ju.6miu.com/read-35964.html

    最新回复(0)