ACM-ICPC 2018 徐州赛区网络预赛 Ryuji doesn't want to study(公式化简+前缀和)

本文介绍了一种使用树状数组求解特定区间内加权和的问题,该问题涉及区间查询和区间更新操作,通过巧妙地转换公式,将原本复杂的区间求和问题转化为两个前缀和的求解。

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

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].

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

That means, if he reads books from l to r, 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 qq 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 nn and qq (n,q≤100000).

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

Then in next qq line each line contains three integers a, b, c, if a=1, it means question type is 1, and bb, ccrepresents [ l , r ]. if a = 2 , it means question type is 2 , and bb, 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

题目来源

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

解析:有a[i]*r-i+1=a[i]*(n-i+1)-a[i]*(n-r),即可化简公式:

(\sum_{i=l}^{r}a[i]*(n-i+1))-(n-r)*\sum_{i=l}^{r}a[i].

画图即可看出就是求两个前缀和。这里我用树状数组进行求前缀和。当然也可以用线段树。

#include<bits/stdc++.h>
using namespace std;

#define e exp(1)
#define pi acos(-1)
#define mod 1000000007
#define inf 0x3f3f3f3f
#define ll long long
#define ull unsigned long long
#define mem(a,b) memset(a,b,sizeof(a))
int gcd(int a,int b){return b?gcd(b,a%b):a;}

const int maxn=1e6+5;
int n,q;
ll a[maxn];
ll c1[maxn],c2[maxn];
int lowbit(int x)
{
	return x&(-x);
}
void add1(int i,ll value)
{
	while(i<=n)
	{
		c1[i]+=value;
		i+=lowbit(i);
	}
}
void add2(int i,ll value)
{
	while(i<=n)
	{
		c2[i]+=value;
		i+=lowbit(i);
	}
}
ll getsum1(int i)
{
	ll ans=0;
	while(i>0)
	{
		ans+=c1[i];
		i-=lowbit(i);
	}
	return ans;
}
ll getsum2(int i)
{
	ll ans=0;
	while(i>0)
	{
		ans+=c2[i];
		i-=lowbit(i);
	}
	return ans;
}

int main()
{
	while(~scanf("%d%d",&n,&q))
	{
		mem(c1,0);mem(c2,0);
		for(int i=1; i<=n; i++)
		{
			scanf("%lld",&a[i]);
			add1(i,a[i]*(n-i+1));
			add2(i,a[i]);
		}
		while(q--)
		{
			int op,x,y;scanf("%d%d%d",&op,&x,&y);
			if(op==1)
			{
				ll ans=getsum1(y)-getsum1(x-1);
				ans-=(getsum2(y)-getsum2(x-1))*(n-y);
				printf("%lld\n",ans); 
			}
			else
			{
				add1(x,(n-x+1)*(y-a[x]));
				add2(x,y-a[x]);
				a[x]=y;
			}
		}
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值