【计蒜客】2018ICPC徐州赛区网络赛H Ryuji doesn't want to study【树状数组】

题目链接

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]a[i].

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

That means, if he reads books from lll to rrr, he will get a[l]×L+a[l+1]×(L−1)+⋯+a[r−1]×2+a[r]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] (LLL is the length of [ lll, rrr ] that equals to r−l+1r - l + 1r−l+1).

Now Ryuji has qqq questions, you should answer him:

111. If the question type is 111, you should answer how much knowledge he will get after he reads books [ lll, rrr ].

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

Input

First line contains two integers nnn and qqq (nnn, q≤100000q \le 100000q≤100000).

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

Then in next qqq line each line contains three integers aaa, bbb, ccc, if a=1a = 1a=1, it means question type is 111, and bbb, ccc represents [ lll , rrr ]. if a=2a = 2a=2 , it means question type is 222 , and bbb, ccc means Ryuji changes the bth book' knowledge to ccc

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

题目来源

ACM-ICPC 2018 徐州赛区网络预赛

 

解题思路:题意很容易理解,就是查和改。将\sum_{i=l}^{r}a[i]*(n-i+1)转化成\sum_{i=l}^{r}a[i]*(n-i+1)-\sum_{i=l}^{r}a[i]*(n-r),只需要用树状数组维护a[i]和a[i]*(n-i+1)这两个前缀和就好,因为a[i]*(n-i+1)结果数据范围超过int,所以计算结果时用long long。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e5+5;
ll sum[maxn][2];
ll a[maxn];
int lowbit(int i)
{
	return i&(-i);
}
void update(int x,ll c,int op)
{
	while(x<maxn)
	{
		sum[x][op]+=c;
		x+=lowbit(x);
	}
}
ll query(int x,int op)
{
	ll ans=0;
	while(x)
	{
		ans+=sum[x][op];
		x-=lowbit(x);
	}
	return ans;
}
int main(void)
{
        freopen("/Users/ZRP/Desktop/input.txt","r",stdin);
	int n,m,op,l,r;
	scanf("%d%d",&n,&m);
	
	for(int i=1;i<=n;i++)
	scanf("%d",&a[i]);
	for(int i=1;i<=n;i++)
	{
		update(i,a[i]*(n-i+1),1);
		update(i,a[i],2);
	}
	for(int i=1;i<=m;i++)
	{
		scanf("%d%d%d",&op,&l,&r);
		if(op==1)
		{
			printf("%lld\n",query(r,1)-query(l-1,1)-(query(r,2)-query(l-1,2))*(n-r));
		}
		else
		{
			update(l,(r-a[l])*(n-l+1),1);
			update(l,r-a[l],2);
			a[l]=r;
		}
	}
	return 0;
 } 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值