Loj 6277 数列分块入门 1

题目链接:https://loj.ac/problem/6277

题面:

题目描述

给出一个长为 nnn 的数列,以及 nnn 个操作,操作涉及区间加法,单点查值。

输入格式

第一行输入一个数字 nnn。

第二行输入 nnn 个数字,第 iii 个数字为 aia_iai​​,以空格隔开。

接下来输入 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,表示询问 ara_rar​​ 的值(lll 和 ccc 忽略)。

输出格式

对于每次询问,输出一行一个数字表示答案。

样例

样例输入

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

样例输出

2
5

数据范围与提示

对于 100% 100\%100% 的数据,1≤n≤50000,−231≤others 1 \leq n \leq 50000, -2^{31} \leq \mathrm{others}1n50000,231​​others、ans≤231−1 \mathrm{ans} \leq 2^{31}-1ans231​​1。

 

思路:

可以用区间修改,单点查询,可以用多种方法求解。下面给出分块和线段树的写法:

分块解法:

假设给了n个元素,我们可以将它分成sqrt(n)组集合,每次区间操作会影响x个块,以及这几个块两边相邻的块中不超过2*sqrt(n)个元素,对于两边的块中需要更新的数我们可以逐个更新本身的值,中间的那些块

用个标记数组存下需要更新的值,最后当前点的值就是本身的值+标记数组中的值。

 

#include<bits/stdc++.h>
using namespace std;
const int M = 1e5+10;
int tag[M],bl[M],v[M],block;
void update(int l,int r,int c){
    for(int i = l;i <= min(bl[l]*block,r);i ++) v[i] += c;
    if(bl[l] != bl[r])
    for(int i = (bl[r]-1)*block+1;i <= r;i++) v[i] += c;
    for(int i = bl[l]+1;i <= bl[r]-1;i ++)
        tag[i] += c;
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    int n,f,l,r,c;
    cin>>n;
    block = sqrt(n);
    for(int i = 1;i <= n;i ++) cin>>v[i];
    for(int i = 1;i <= n;i ++) bl[i] = (i-1)/block+1;
    while(n--){
        cin>>f>>l>>r>>c;
        if(f == 0) update(l,r,c);
        else cout<<v[r] + tag[bl[r]]<<endl;
    }
    return 0;
}

 

线段树解法:

#include<bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define mid int m = (l + r) >> 1
const int M = 1e5+10;
int lazy[M<<2],sum[M<<2];
int a[M],n;
void pushdown(int l,int r,int rt){
    if(lazy[rt]){
        int m = r - l + 1;
        lazy[rt<<1] += lazy[rt];
        lazy[rt<<1|1] += lazy[rt];
        sum[rt<<1] += (m - (m>>1))*lazy[rt];
        sum[rt<<1|1] += (m>>1)*lazy[rt];
        lazy[rt] = 0;
    }
}

void build(int l,int r,int rt){
    lazy[rt] = 0;
    if(l == r) {
        sum[rt] = a[l];
        return ;
    }
    mid;
    build(lson);
    build(rson);
}

void update(int L,int R,int c,int l,int r,int rt){
    if(L <= l&&R >= r){
        sum[rt] += (r-l+1)*c;
        lazy[rt] += c;
        return ;
    }
    pushdown(l,r,rt);
    mid;
    if(L <= m) update(L,R,c,lson);
    if(R > m) update(L,R,c,rson);
}

int query(int p,int l,int r,int rt){
    if(l == r){
        return sum[rt];
    }
    pushdown(l,r,rt);
    mid;
    if(p <= m) return query(p,lson);
    else return query(p,rson);
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    int f,l,r,c;
    cin>>n;
    for(int i = 1;i <= n;i ++) cin>>a[i];
    build(1,n,1);
    for(int i = 1;i <= n;i ++){
        cin>>f>>l>>r>>c;
        if(f == 0) update(l,r,c,1,n,1);
        else cout<<query(r,1,n,1)<<endl;
    }
    return 0;
}

两种解法耗时都差不多,不过线段树代码量明显更大。

posted @ 2018-06-03 17:22  冥想选手  阅读(213)  评论(0编辑  收藏  举报