1. 程式人生 > >LOJ#6278. 數列分塊入門 2

LOJ#6278. 數列分塊入門 2

pla lower 標準 tag href discuss scu inf 一個數

內存限制:256 MiB時間限制:500 ms標準輸入輸出 題目類型:傳統評測方式:文本比較 上傳者: hzwer 提交提交記錄統計討論測試數據

題目描述

給出一個長為 nnn 的數列,以及 nnn 個操作,操作涉及區間加法,詢問區間內小於某個值 xxx 的元素個數。

輸入格式

第一行輸入一個數字 nnn。

第二行輸入 nnn 個數字,第 i 個數字為 aia_ia?i??,以空格隔開。

接下來輸入 nnn 行詢問,每行輸入四個數字 opt\mathrm{opt}opt、lll、rrr、ccc,以空格隔開。

opt=0\mathrm{opt} = 0opt=0,表示將位於 [l,r][l, r][l,r] 的之間的數字都加 ccc。

opt=1\mathrm{opt} = 1opt=1,表示詢問 [l,r][l, r][l,r] 中,小於 c2c^2c?2?? 的數字的個數。

輸出格式

對於每次詢問,輸出一行一個數字表示答案。

樣例

樣例輸入

4
1 2 2 3
0 1 3 1
1 1 3 2
1 1 4 1
1 2 3 2

樣例輸出

3
0
2

數據範圍與提示

對於 100% 100\%100% 的數據,1≤n≤50000,−231≤others 1 \leq n \leq 50000, -2^{31} \leq \mathrm{others}1n50000,2?31??others、ans≤231−1 \mathrm{ans} \leq 2^{31}-1ans2?31??1。

對於區間和我們可以按照正常思路做。

對於第二個詢問,我們可以用vector維護每個塊內的有序表,

零散的塊直接暴力,否則在vector內二分

註意vector的編號是從0開始的

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
using namespace std;
const int MAXN=1e6+10;
const int INF=1e8+10;
inline char nc()
{
    static char buf[MAXN],*p1=buf,*p2=buf;
    return p1==p2&&(p2=(p1=buf)+fread(buf,1,MAXN,stdin),p1==p2)?EOF:*p1++;
}
inline int read()
{
    char c=nc();int x=0,f=1;
    while(c<0||c>9){if(c==-)f=-1;c=nc();}
    while(c>=0&&c<=9){x=x*10+c-0;c=nc();}
    return x*f;
}
vector<int>v[1001];//用vector儲存分塊後塊內的有序表
int block,L[MAXN],R[MAXN],a[MAXN],tag[MAXN],belong[MAXN],N;
void Sort(int p)
{
    v[p].clear();
    for(int i=L[p*block];i<=min(R[p*block],N);i++)
        v[p].push_back(a[i]);
    sort(v[p].begin(),v[p].end());
}
void IntervalAdd(int l,int r,int val)
{
    for(int i=l;i<=min(r,R[l]);i++) a[i]+=val;
    Sort(belong[l]);
    if(belong[l]!=belong[r])
    {
        for(int i=L[r];i<=r;i++)     a[i]+=val;
        Sort(belong[r]);
    }
    for(int i=belong[l]+1;i<=belong[r]-1;i++) tag[i]+=val;    
}
int Query(int l,int r,int val)
{
    int ans=0;
    for(int i=l;i<=min(r,R[l]);i++) 
        if(a[i]+tag[belong[l]]<val) ans++;
    if(belong[l]!=belong[r])
        for(int i=L[r];i<=r;i++)
            if(a[i]+tag[belong[r]]<val) ans++;
    for(int i=belong[l]+1;i<=belong[r]-1;i++)
    {
        int x=val-tag[i];
        ans+=lower_bound(v[i].begin(),v[i].end(),x)-v[i].begin();
    }
    return ans;
}
int main()
{
    #ifdef WIN32
    freopen("a.in","r",stdin);
    freopen("b.out","w",stdout);
    #else
    #endif
    N=read();block=sqrt(N);
    for(int i=1;i<=N;i++) a[i]=read();
    for(int i=1;i<=N;i++) belong[i]=(i-1)/block+1,L[i]=(belong[i]-1)*block+1,R[i]=belong[i]*block;
    for(int i=1;i<=N;i++) v[belong[i]].push_back(a[i]);
    for(int i=1;i<=belong[N];i++) Sort(i);
    for(int i=1;i<=N;i++)
    {
        int opt=read(),l=read(),r=read(),c=read();
        if(opt==0) IntervalAdd(l,r,c);
        else        printf("%d\n",Query(l,r,c*c));
    }
    return 0;
}

LOJ#6278. 數列分塊入門 2