4fd800b3a8 2011-02-23 kinaba: //------------------------------------------------------------- 4fd800b3a8 2011-02-23 kinaba: // Range Minimum Query 4fd800b3a8 2011-02-23 kinaba: // O(N log N) construction 4fd800b3a8 2011-02-23 kinaba: // O(1) per each query 4fd800b3a8 2011-02-23 kinaba: // returns the LEFTMOST/ALL minimum index (I hope) 4fd800b3a8 2011-02-23 kinaba: // 4fd800b3a8 2011-02-23 kinaba: // Verified by 4fd800b3a8 2011-02-23 kinaba: // - SRM337 Div1 LV2 4fd800b3a8 2011-02-23 kinaba: // - SRM431 Div1 LV3 4fd800b3a8 2011-02-23 kinaba: //------------------------------------------------------------- 4fd800b3a8 2011-02-23 kinaba: 4fd800b3a8 2011-02-23 kinaba: template<typename T> 4fd800b3a8 2011-02-23 kinaba: struct RMQ 4fd800b3a8 2011-02-23 kinaba: { 4fd800b3a8 2011-02-23 kinaba: vector< vector<int> > rm; 4fd800b3a8 2011-02-23 kinaba: vector<T> d; 4fd800b3a8 2011-02-23 kinaba: 4fd800b3a8 2011-02-23 kinaba: RMQ( const vector<T>& d ) : d(d) { 4fd800b3a8 2011-02-23 kinaba: int n = d.size(); 4fd800b3a8 2011-02-23 kinaba: 4fd800b3a8 2011-02-23 kinaba: // rm[k][x] = i s.t. d[i] is the minimum in [x, x+2^k) 4fd800b3a8 2011-02-23 kinaba: rm.push_back( vector<int>(n) ); 4fd800b3a8 2011-02-23 kinaba: for(int x=0; x<n; ++x) 4fd800b3a8 2011-02-23 kinaba: rm[0][x] = x; 4fd800b3a8 2011-02-23 kinaba: for(int k=1; (1<<k)<=n; ++k) { 4fd800b3a8 2011-02-23 kinaba: rm.push_back( rm[k-1] ); 4fd800b3a8 2011-02-23 kinaba: for(int x=0; x+(1<<k-1)<n; ++x) 4fd800b3a8 2011-02-23 kinaba: if( d[rm[k][x]] > d[rm[k-1][x + (1<<k-1)]] ) 4fd800b3a8 2011-02-23 kinaba: rm[k][x] = rm[k-1][x + (1<<k-1)]; 4fd800b3a8 2011-02-23 kinaba: } 4fd800b3a8 2011-02-23 kinaba: } 4fd800b3a8 2011-02-23 kinaba: 4fd800b3a8 2011-02-23 kinaba: int operator()(int L, int R) const { // inclusive 4fd800b3a8 2011-02-23 kinaba: int k=0; 4fd800b3a8 2011-02-23 kinaba: for(; L+(1<<k) < R-(1<<k)+1; ++k) {} 4fd800b3a8 2011-02-23 kinaba: LL i = rm[k][L]; 4fd800b3a8 2011-02-23 kinaba: LL j = rm[k][R-(1<<k)+1]; 4fd800b3a8 2011-02-23 kinaba: return (d[i]<=d[j] ? i : j); 4fd800b3a8 2011-02-23 kinaba: } 4fd800b3a8 2011-02-23 kinaba: 4fd800b3a8 2011-02-23 kinaba: vector<int> all(int L, int R) const { 4fd800b3a8 2011-02-23 kinaba: vector<int> ans; 4fd800b3a8 2011-02-23 kinaba: int minValue = d[(*this)(L, R)]; 4fd800b3a8 2011-02-23 kinaba: while( L <= R ) { 4fd800b3a8 2011-02-23 kinaba: int C = (*this)(L, R); 4fd800b3a8 2011-02-23 kinaba: if( minValue < d[C] ) 4fd800b3a8 2011-02-23 kinaba: break; 4fd800b3a8 2011-02-23 kinaba: ans.push_back(C); 4fd800b3a8 2011-02-23 kinaba: L = C+1; 4fd800b3a8 2011-02-23 kinaba: } 4fd800b3a8 2011-02-23 kinaba: return ans; 4fd800b3a8 2011-02-23 kinaba: } 4fd800b3a8 2011-02-23 kinaba: };