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

本文介绍了一道编程题的解决思路,利用线段树和树状数组处理区间查询与更新问题,详细解释了如何将双变量问题转换为两棵树状数组的维护,以高效解答区间内特定形式的求和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值