區間加法,區間求前驅。html
這題的方法與分塊2方法極其相似,建議自行解決。spa
和上一題相似,可是二分不是用來計數的,而是用來求小於c的最大值的。而後對於不完整快,將小於c的值求最大值,再與全部塊中二分結果求最大值便可。(其餘思路上一篇題解已經講了,這裏再也不復述,代碼註釋也懶得打了,由於比較簡單,很容易理解)code
#include<cstdio> #include<vector> #include<algorithm> #include<cmath> using namespace std; #define MAXN 100005 int n, m, a[MAXN], p[MAXN], b[1005], mm; vector<int> v[1005]; int opt, l, r, c; int EF( vector<int> vec, int x ){ int l, r, mid, ans(-1); l = 0; r = vec.size() - 1; while( l <= r ){ mid = ( l + r ) >> 1; if ( vec[mid] < x ){ ans = mid; l = mid + 1; } else r = mid - 1; } return ans; } int query( int l, int r, int c ){ int ans(-1); if ( p[l] == p[r] ){ for ( int i = l; i <= r; ++i ) if ( a[i] + b[p[l]] < c ) ans = max( ans, a[i] + b[p[l]] ); return ans; } for ( int i = l; p[i] == p[l]; ++i ) if ( a[i] + b[p[i]] < c ) ans = max( ans, a[i] + b[p[l]] ); for ( int i = r; p[i] == p[r]; --i ) if ( a[i] + b[p[i]] < c ) ans = max( ans, a[i] + b[p[r]] ); for ( int i = p[l] + 1; i <= p[r] - 1; ++i ){ int t(EF( v[i], c - b[i] )); if ( t >= 0 ) ans = max( ans, v[i][t] + b[i] ); } return ans; } void re( int x ){ v[x].clear(); int be(( x - 1 ) * m + 1); for ( int i = be; p[i] == p[be]; i++ ) v[x].push_back( a[i] ); sort( v[x].begin(), v[x].end() ); } void Add( int l, int r, int c ){ if ( p[l] == p[r] ){ for ( int i = l; i <= r; ++i ) a[i] += c; re( p[l] ); return; } for ( int i = l; p[i] == p[l]; ++i ) a[i] += c; re(p[l]); for ( int i = r; p[i] == p[r]; --i ) a[i] += c; re(p[r]); for ( int i = p[l] + 1; i < p[r]; ++i ) b[i] += c; } int main(){ scanf( "%d", &n ); m = (int)sqrt(n); for ( int i = 1; i <= n; ++i ) p[i] = ( i - 1 ) / m + 1, mm = p[i]; for ( int i = 1; i <= n; ++i ) scanf( "%d", &a[i] ); for ( int i = 1; i <= n; ++i ) v[p[i]].push_back(a[i]); for ( int i = 1; i <= mm; ++i ) sort( v[i].begin(), v[i].end() ); for ( int i = 1; i <= n; ++i ){ scanf( "%d%d%d%d", &opt, &l, &r, &c ); if ( opt ) printf( "%d\n", query( l, r, c ) ); else Add( l, r, c ); } return 0; }
分塊切記要舉一反三,充分發揮分塊的靈活性。htm
數列分塊入門1blog
數列分塊入門2get
數列分塊入門3 <-it
數列分塊入門4io
數列分塊入門5入門
數列分塊入門6class