1. 程式人生 > >2018 ICPC徐州網路賽 H.Ryuji doesn't want to study (樹狀陣列)

2018 ICPC徐州網路賽 H.Ryuji doesn't want to study (樹狀陣列)

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;
}