ACM/ICPC 2018 徐州网络赛 H题 Ryuji doesn't want to study

题目链接:https://nanti.jisuanke.com/t/31460

Ryuji is not a good student, and he doesn't want to study. But there are n books he should learn, each book has its knowledge a[i]a[i].

Unfortunately, the longer he learns, the fewer he gets.

That means, if he reads books from ll to rr, he will get a[l] \times L + a[l+1] \times (L-1) + \cdots + a[r-1] \times 2 + a[r]a[l]×L+a[l+1]×(L−1)+⋯+a[r−1]×2+a[r] (LL is the length of [ ll, rr ] that equals to r - l + 1r−l+1).

Now Ryuji has qq questions, you should answer him:

11. If the question type is 11, you should answer how much knowledge he will get after he reads books [ ll, rr ].

22. If the question type is 22, Ryuji will change the ith book's knowledge to a new value.

Input

First line contains two integers nn and qq (nn, q \le 100000q≤100000).

The next line contains n integers represent a[i]( a[i] \le 1e9)a[i](a[i]≤1e9) .

Then in next qq line each line contains three integers aa, bb, cc, if a = 1a=1, it means question type is 11, and bb, ccrepresents [ ll , rr ]. if a = 2a=2 , it means question type is 22 , and bb, cc means Ryuji changes the bth book' knowledge to cc

Output

For each question, output one line with one integer represent the answer.

样例输入复制

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

样例输出复制

10
8

题意:1.求 

2 。 更新a[l] 为 w

题解:对于任意一项 i,它对区间和的贡献为 a[i]*(r-i+1) (r为区间右端点),因此上式可化为

可以进一步化简为 (r+1)\sum_{i=1}^r a[i] - \sum_{i=l}^r a[i]*i  ,那么只要求a[i]的前缀和以及i*a[i]的前缀和就行了。

树状数组

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<stdio.h>
#include<string.h>
#include<queue>
#include<cmath>
#include<map>
#include<set>
#include<vector> 
using namespace std;
#define inf 0x3f3f3f
#define rep(i,a,n) for(int i=a;i<=n;i++)
#define per(i,a,n) for(int i=n;i>=a;i--)
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define mem(a,b) memset(a,b,sizeof(a));
#define lowbit(x)  x&-x;
typedef long long ll;
const int maxn = 1e5+5;
int n,q;
//更新两个前缀和 
ll c1[maxn],c2[maxn];
ll a[maxn];
void update1(int x,ll val){
	while(x <= n){
		c1[x] += val;
		x += lowbit(x);
	}
}
ll sum1(int x){
	ll res = 0;
	while(x > 0){
		res += c1[x];
		x -= lowbit(x);
	}
	return res;
}
void update2(int x,ll val){
	while(x <= n){
		c2[x] += val;
		x += lowbit(x);
	}
}
ll sum2(int x){
	ll res = 0;
	while(x > 0){
		res += c2[x];
		x -= lowbit(x);
	}
	return res;
}
int main(){
	while(~scanf("%d%d",&n,&q)){
		mem(c1,0);
		mem(c2,0);
		int op,l,r;
		for(int i = 1; i <= n; i++){
			scanf("%lld",&a[i]);
		}
		for(int i = 1; i <= n; i++){
			update1(i,a[i]);
			update2(i,i*a[i]);
		}
		ll ans = 0;
		for(int i = 1; i <= q; i++){
			scanf("%d%d%d",&op,&l,&r);
			if(op == 1){
				ans = (r+1)*(sum1(r) - sum1(l-1));
				ans -= (sum2(r) - sum2(l-1));
				printf("%lld\n",ans);	
			}else{
				update1(l,r-a[l]);
				update2(l,l*(r-a[l]));
				a[l] = r;
			}
		}
	}
} 

猜你喜欢

转载自blog.csdn.net/pall_scall/article/details/82562181