Preprefix sum BZOJ 3155 树状数组

题目描述

前缀和(prefix sum)Si=∑k=1iaiS_i=\sum_{k=1}^i a_iSi=k=1iai

前前缀和(preprefix sum) 则把SiS_iSi作为原序列再进行前缀和。记再次求得前缀和第i个是SSiSS_iSSi

给一个长度n的序列a1,a2,⋯,ana_1, a_2, \cdots, a_na1,a2,,an,有两种操作:

  1. Modify i x:把aia_iai改成xxx;
  2. Query i:查询SSiSS_iSSi

输入输出格式

输入格式:

第一行给出两个整数N,M。分别表示序列长度和操作个数
接下来一行有N个数,即给定的序列a1,a2,....an
接下来M行,每行对应一个操作,格式见题目描述

输出格式:

对于每个询问操作,输出一行,表示所询问的SSi的值。

输入输出样例

输入样例#1: 复制
5 3
1 2 3 4 5
Query 5
Modify 3 2 Query 5
输出样例#1: 复制
35
32

说明

1<=N,M<=100000,且在任意时刻0<=Ai<=100000

维护两个数组:a[i], (n-i+1)a[i];

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<string>
#include<cmath>
#include<map>
#include<set>
#include<vector>
#include<queue>
#include<bitset>
#include<ctime>
#include<deque>
#include<stack>
#include<functional>
#include<sstream>
//#include<cctype>
//#pragma GCC optimize(2)
using namespace std;
#define maxn 200005
#define inf 0x7fffffff
//#define INF 1e18
#define rdint(x) scanf("%d",&x)
#define rdllt(x) scanf("%lld",&x)
#define rdult(x) scanf("%lu",&x)
#define rdlf(x) scanf("%lf",&x)
#define rdstr(x) scanf("%s",x)
typedef long long  ll;
typedef unsigned long long ull;
typedef unsigned int U;
#define ms(x) memset((x),0,sizeof(x))
const long long int mod = 1e9;
#define Mod 1000000000
#define sq(x) (x)*(x)
#define eps 1e-11
typedef pair<int, int> pii;
#define pi acos(-1.0)
//const int N = 1005;
#define REP(i,n) for(int i=0;i<(n);i++)
typedef pair<int, int> pii;

inline int rd() {
	int x = 0;
	char c = getchar();
	bool f = false;
	while (!isdigit(c)) {
		if (c == '-') f = true;
		c = getchar();
	}
	while (isdigit(c)) {
		x = (x << 1) + (x << 3) + (c ^ 48);
		c = getchar();
	}
	return f ? -x : x;
}


ll gcd(ll a, ll b) {
	return b == 0 ? a : gcd(b, a%b);
}
int sqr(int x) { return x * x; }



/*ll ans;
ll exgcd(ll a, ll b, ll &x, ll &y) {
	if (!b) {
		x = 1; y = 0; return a;
	}
	ans = exgcd(b, a%b, x, y);
	ll t = x; x = y; y = t - a / b * y;
	return ans;
}
*/

ll a[maxn];
ll b[2][maxn];

int n, m;

void add(int x, ll val, int dx) {
	while (x <= n) {
		b[dx][x] += val; x += x & -x;
	}
}
void upd(int pos, ll val) {
	add(pos, -a[pos], 0); add(pos, -a[pos] * (n - pos + 1), 1);
	a[pos] = val;
	add(pos, a[pos], 0); add(pos, a[pos] * (n - pos + 1), 1);
}
ll query(int x) {
	ll ans = 0;
	int tmp = x;
	while (tmp > 0) {
		ans += b[1][tmp]; tmp -= tmp & -tmp;
	}
	tmp = x; ll res = 0;
	while (tmp > 0) {
		res += b[0][tmp]; tmp -= tmp & -tmp;
	}
	return ans - (n - x)*res;
}

int main() {
//	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	n = rd(); m = rd();
	for (int i = 1; i <= n; i++) {
		rdllt(a[i]);
		add(i, a[i], 0); add(i, (n - i + 1)*a[i], 1);
	}
	while (m--) {
		char ch[10];
		rdstr(ch);
		if (ch[0] == 'M') {
			int pos; ll val;
			rdint(pos); rdllt(val);
			upd(pos, val);
		}
		else {
			int pos; pos = rd();
			printf("%lld\n", query(pos));
		}
	}
	return 0;
}

 

posted @ 2019-01-31 09:32  NKDEWSM  阅读(289)  评论(0编辑  收藏  举报