「分塊系列」數列分塊入門2 解題報告

數列分塊入門2

題意歸納

區間加法,區間詢問小於一個數的個數。html

正題

對於每一個塊,除原數組以外用一個vector來有序地存儲全部數。當區間加時,對於每一個完整塊維護共同加數,對於不完整的塊直接暴力加上再從新排序。當詢問時,對於每一個完整塊在vector中二分,對於不完整的,直接暴力計數。算法

代碼

#include<cstdio>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
#define MAXN 50005

int n, m, a[MAXN], p[MAXN], b[500], mm;
vector<int> v[500];
int opt, l, r, c;

int EF( vector<int> vec, int x ){//自力更生,手打二分萬歲QAQ
    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 + 1;
}

int query( int l, int r, int c ){
    int ans(0);
    
    if ( p[l] == p[r] ){
        for ( int i = l; i <= r; ++i )
            if ( a[i] + b[p[l]] < c ) ans++;
        return ans;
    }
    
    for ( int i = l; p[i] == p[l]; ++i )
        if ( a[i] + b[p[i]] < c ) ans++;
    for ( int i = r; p[i] == p[r]; --i )
        if ( a[i] + b[p[i]] < c ) ans++;
    for ( int i = p[l] + 1; i <= p[r] - 1; ++i )
        ans += EF( v[i], c - 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]);//重排。實際上能夠歸併排序,或者要用時再臨時排序,這裏偷了懶QAQ
    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 * c ) );
        else Add( l, r, c );
    }
    return 0;
}

總結

比起其餘算法老長老長的代碼,分塊算法的靈活在本題中獲得體現QAQ數組

數列分塊系列目錄

數列分塊入門1spa

數列分塊入門2 <-code

數列分塊入門3htm

數列分塊入門4blog

數列分塊入門5排序

數列分塊入門6get

數列分塊入門7it

數列分塊入門8

數列分塊入門9

蒲公英

公主的朋友

相關文章
相關標籤/搜索