【LibreOJ】#6277. 数列分块入门 1 分块模板题

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

输入格式
第一行输入一个数字 。

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

接下来输入 行询问,每行输入四个数字 、、、,以空格隔开。

若 ,表示将位于 的之间的数字都加 。

若 ,表示询问 的值( 和 忽略)。

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

样例
样例输入
4
1 2 2 3
0 1 3 1
1 0 1 0
0 1 2 2
1 0 2 0
样例输出
2
5

AC代码:

#include<iostream>
#include<string>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include <queue>
#include<sstream>
#include <stack>
#include <set>
#include <bitset>
#include<vector>
#define FAST ios::sync_with_stdio(false)
#define abs(a) ((a)>=0?(a):-(a))
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(),(x).end()
#define mem(a,b) memset(a,b,sizeof(a))
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))
#define rep(i,a,n) for(int i=a;i<=n;++i)
#define per(i,n,a) for(int i=n;i>=a;--i)
#define pb push_back
#define mp make_pair
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef pair<ll,ll> PII;
const int maxn = 1e5+200;
const int inf=0x3f3f3f3f;
const double eps = 1e-7;
const double pi=acos(-1.0);
const int mod = 1e9+7;
inline int lowbit(int x){return x&(-x);}
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
void ex_gcd(ll a,ll b,ll &d,ll &x,ll &y){if(!b){d=a,x=1,y=0;}else{ex_gcd(b,a%b,d,y,x);y-=x*(a/b);}}//x=(x%(b/d)+(b/d))%(b/d);
inline ll qpow(ll a,ll b,ll MOD=mod){ll res=1;a%=MOD;while(b>0){if(b&1)res=res*a%MOD;a=a*a%MOD;b>>=1;}return res;}
inline ll inv(ll x,ll p){return qpow(x,p-2,p);}
inline ll Jos(ll n,ll k,ll s=1){ll res=0;rep(i,1,n+1) res=(res+k)%i;return (res+s)%n;}
inline ll read(){ ll f = 1; ll x = 0;char ch = getchar();while(ch>'9'||ch<'0') {if(ch=='-') f=-1; ch = getchar();}while(ch>='0'&&ch<='9') x = (x<<3) + (x<<1) + ch - '0',  ch = getchar();return x*f; }
int dir[4][2] = { {1,0}, {-1,0},{0,1},{0,-1} };

ll a[maxn];     //原序列
ll L[maxn];     //这个块的左端点
ll R[maxn];     //这个块的右端点
ll pos[maxn];   //第i个位置所属块
ll add[maxn];   //用来给第i个块记录偏移量
ll n;

void Add(ll l, ll r, ll c)
{
    ll p = pos[l], q = pos[r];
    if(p==q) rep(i,l,r) a[i] += c;
    else
    {
        rep(i,l,R[p])  a[i] += c;
        rep(i,L[q],r) a[i] += c;
        rep(i,p+1,q-1) add[i] += c;
    }
}

int main()
{
    n = read();
    ll block = sqrt(n*1.0);
    ll num = ceil(n*1.0/block);
    rep(i,1,n) a[i] = read(), pos[i] = (i-1)/block + 1;
    rep(i,1,num) L[i] = (i-1)*block + 1 , R[i] = block * i;
    rep(i,1,n)
    {
        ll flag = read(), l = read(), r = read(), c = read();
        if(!flag)  Add(l,r,c);
        else printf("%lld\n",a[r] + add[pos[r]]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_45492531/article/details/107813036