2018 ICPC徐州网络赛 H.Ryuji doesn't want to study (树状数组)

版权声明:如果路过的各位大佬想对菜鸡进行指点请加QQ:3360769137 https://blog.csdn.net/PleasantlY1/article/details/83752583

Ryuji is not a goodstudent, and he doesn't want to study. But there are n books he should learn, each book has its knowledge 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] (L is the length of [ l, r ] that equals to r−l+1).

Now Ryuji has q questions, you should answer him:

1. If the question type is 1, you should answer how much knowledge he will get after he reads books [ l, r ].

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

Input

First line contains two integers n and q (n, q≤100000).

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

Then in next q line each line contains three integers a, b, c, if a=1, it means question type is 1, and b, c represents [ l, r ]. if a=2 , it means question type is 2 , and b, c means Ryuji changes the bth book' knowledge to c

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

题目大意:给出一个序列,m个操作,有2种操作,修改第x个数的值,查询l到r区间内,a[l]×L+a[l+1]×(L−1)+⋯+a[r−1]×2+a[r] (L 为区间(l,r)的长度).

思路:这种操作挺熟悉。线段树?树状数组?emm,2个变量啊,,怎么处理呢。

整理一下所求的式子:

所以将2个变量拆分出来,(n-i+1)*a[i]-(n-r)*a[i]   i∈(l,r)   用2个树状数组分别维护(n-i+1)*a[i]与a[i]的前缀和即可。

代码如下:

#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<string.h>
#include<string>
#include<map>
#include<set>
#include<queue>
#define per(i,a,b) for(int i=a;i<=b;++i)
#define ll long long 
using namespace std;
ll p[100005],n,m,p1[100005];
ll lowbit(ll k)
{
	return k&(-k);
}

void add(int x,ll y,int fag)
{
	for(int i=x;i<=n;i+=lowbit(i))
	{
		if(fag==1) p[i]+=y;
		if(fag==2) p1[i]+=y;
	}
}

ll find(ll x,int fag)
{
	ll s=0;
	for(int i=x;i>0;i-=lowbit(i))
	{
		if(fag==1) s+=p[i];
		if(fag==2) s+=p1[i];
	}
	return s;
}
int main()
{
	cin>>n>>m;
	per(i,1,n) 
	{
	   ll t;
	   cin>>t;
	   add(i,t,1);
	   add(i,t*(n-i+1),2);
    }
	while(m--)
	{
		int a,x,y;
		cin>>a>>x>>y;
		if(a==1)
		{
			ll s1=find(y,2)-find(x-1,2);
			ll s2=find(y,1)-find(x-1,1);
			printf("%lld\n",s1-s2*(n-y));
		}
		if(a==2)
		{
			ll z=find(x,1)-find(x-1,1);
			add(x,y-z,1);
			add(x,(y-z)*(n-x+1),2);
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/PleasantlY1/article/details/83752583