题解 | 【模板】静态区间和(前缀和)

【模板】静态区间和(前缀和)

https://www.nowcoder.com/practice/ac79a1a4a66646cc87525d6faa86e021

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

using ll=long long;
using ull=unsigned long long;
using i128=__int128_t;
using u128=__uint128_t;
using ld=long double;

void solve()
{
	int n,q,l,r;
	cin >> n >> q;
	vector<ll>v(n+1,0),pre(n+1,0);//原数组和前缀和数组 可以多开一个空间 方便构建数组
	for(int i=1;i<=n;i++) cin >> v[i];
	for(int i=1;i<=n;i++) pre[i]=pre[i-1]+v[i];
	while(q--)//pre[i]表示前i个元素相加的和 于是我们可以用某两个pre数组的元素相减得到某个区间的和
	{
		cin >> l >> r;
		cout << pre[r]-pre[l-1] << "\n";
	}
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	
	int t=1;
	//cin >> t;
	
	while(t--)
	{
		solve();
	}
	return 0;
}

全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务