第一次RMQ ,还好
RMQ版:
# include <cstdio> # include <iostream> # include <set> # include <map> # include <vector> # include <list> # include <queue> # include <stack> # include <cstring> # include <string> # include <cstdlib> # include <cmath> # include <algorithm> using namespace std ; const int maxn = 51000 ; int dp1 [ 20 ] [ maxn ] ; int dp2 [ 20 ] [ maxn ] ; //小的放前面效率高不少 int a [ 51000 ] ; int n ; void getdp ( ) { for ( int i = 1 ; i <= n ; i ++ ) { dp1 [ 0 ] [ i ] = dp2 [ 0 ] [ i ] = a [ i ] ; } int len = floor ( log2 ( 51000 ) ) ; //C++没有log2,取自然对数算 for ( int j = 1 ; j <= len ; j ++ ) for ( int i = 1 ; i + ( 1 << j ) - 1 <= n ; i ++ ) { dp1 [ j ] [ i ] = min ( dp1 [ j - 1 ] [ i ] , dp1 [ j - 1 ] [ i + (1 << (j - 1)) ] ) ; dp2 [ j ] [ i ] = max ( dp2 [ j - 1 ] [ i ] , dp2 [ j - 1 ] [ i + (1 << (j - 1)) ] ) ; } } int main ( ) { int q ; scanf ( "%d%d" , & n , & q ) ; for ( int i = 1 ; i <= n ; i ++ ) { scanf ( "%d" , a + i ) ; } getdp ( ) ; while ( q -- ) { int m , n ; scanf ( "%d%d" , & m , & n ) ; int len = floor ( log2 ( n - m + 1 ) ) ; int maxx = max ( dp2 [ len ] [ m ] , dp2 [ len ] [ n - ( 1 << len ) + 1 ] ) ; int minn = min ( dp1 [ len ] [ m ] , dp1 [ len ] [ n - ( 1 << len ) + 1 ] ) ; printf ( "%d\n" , maxx - minn ) ; } }
# include <cstdio> # include <iostream> # include <set> # include <map> # include <vector> # include <list> # include <queue> # include <stack> # include <cstring> # include <string> # include <cstdlib> # include <cmath> # include <algorithm> using namespace std ; const int maxn = 51000 ; const int MAX = 2100000000 ; int low , high ; struct Tree { int maxx , minn ; } tree [ maxn * 4 ] ; void pushup ( int pos ) { tree [ pos ] . minn = min ( tree [ pos * 2 ] . minn , tree [ pos * 2 + 1 ] . minn ) ; tree [ pos ] . maxx = max ( tree [ pos * 2 ] . maxx , tree [ pos * 2 + 1 ] . maxx ) ; } void build ( int l , int r , int pos ) { if ( l == r ) { scanf ( "%d" , & tree [ pos ] . minn ) ; tree [ pos ] . maxx = tree [ pos ] . minn ; return ; } int m = ( l + r ) / 2 ; build ( l , m , pos * 2 ) ; build ( m + 1 , r , pos * 2 + 1 ) ; pushup ( pos ) ; } void quer ( int l , int r , int pos , int L , int R ) { if ( l >= L && r <= R ) { high = max ( high , tree [ pos ] . maxx ) ; low = min ( low , tree [ pos ] . minn ) ; return ; } int m = ( l + r ) / 2 ; if ( m >= L ) quer ( l , m , pos * 2 , L , R ) ; if ( m + 1 <= R ) quer ( m + 1 , r , pos * 2 + 1 , L , R ) ; } int main ( ) { int n , q ; scanf ( "%d%d" , & n , & q ) ; build ( 1 , n , 1 ) ; while ( q -- ) { int L , R ; scanf ( "%d%d" , & L , & R ) ; high = 0 , low = MAX ; quer ( 1 , n , 1 , L , R ) ; printf ( "%d\n" , high - low ) ; } }