题意:给一个序列,有两种操作:操作1对给定区间内值加x,操作2求序列某点值
思路:取一个差分数组b[i]=a[i]-a[i-1]
,则b中i的前缀和表示a[i]
中i点的值,故由区间修改单点查询转化为了区间查询单点修改,区间修改时使用差分add(l, x)
和add(r+1, -x)
,查询某点值时直接求sum就行
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define lowbit(x) (x&-x)
using namespace std;
typedef long long ll;
const ll maxn = 1000005;
ll c[maxn], n, q, a[maxn], b[maxn];
void add(ll x, ll t)
{
for (; x <= n; x += lowbit(x)) {
c[x] += t;
}
}
ll sum(ll x)
{
ll s = 0;
for (; x; x -= lowbit(x)) {
s += c[x];
}
return s;
}
int main()
{
while (cin >> n >> q) {
for (ll i = 1; i <= n; i++) {
cin >> a[i];
}
b[1] = a[1];
for (ll i = 2; i <= n; i++)
b[i] = a[i] - a[i-1];
for (ll i = 1; i <= n; i++)
for (ll j = i; j > i-lowbit(i); j--) {
c[i] += b[j];
}
for (ll i = 0; i < q; i++) {
ll k;
cin >> k;
if (k == 1) {
ll l, r, x;
cin >> l >> r >> x;
add(l, x);
add(r+1, -x);
}
if (k == 2) {
ll x;
cin >> x;
cout << sum(x) << endl;
}
}
}
}