跳到正文

题解

题解:SP14543 RANGESUM - Range Sum

Fake_Cry约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年12月28日
收录
2025年12月28日
更新
2026年11月16日
篇幅
约 2 分钟
题目
SP14543

版本

  1. v1当前

题解:SP14543 RANGESUM - Range Sum

题意题目里已经很清楚了。

思路

核心:用两个部分分别存储数据,并提前算好各自的前缀和,查询时通过下标分段计算。

把原始数组和插入到头部的数分开存储,分别计算它们的前缀和。

每次插入时,将新数追加到“头部数组”的末尾并更新其前缀和。

查询区间和时,根据当前头部数组的长度,将查询区间拆成“头部数组段”和“原始数组段”两部分,分别用前缀和差分快速求和,再合并结果,这样每次操作都不需要循环了。

代码

可以使用 vjudge 提交。

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=2e5+5;
int a[N],pre[N],f[N],pf[N];
void solve(){
	int n;
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>a[i];
		pre[i]=pre[i-1]+a[i];
	}
	int q;
	cin>>q;
	int k=0;
	pf[0]=0;
	while(q--){
		int t;
		cin>>t;
		if(t==1){
			int l,r;
			cin>>l>>r;
			int ans=0;
			if(r<=k){
				ans=pf[k-l+1]-pf[k-r];
			}else if(l>k){
				ans=pre[r-k]-pre[l-k-1];
			}else{
				ans+=pf[k-l+1];
				ans+=pre[r-k];
			}
			cout<<ans<<'\n';
		}else{
			int x;
			cin>>x;
			k++;
			f[k]=x;
			pf[k]=pf[k-1]+x;
		}
	}
}
signed main(){
	cin.tie(0)->sync_with_stdio(0);
	cout.tie(0);
	solve();
	return 0;
}
原文
存档评论1 条抓取于