【模板】序列前缀和

Description

你需要维护 N 个整数组成的序列,支持 Q 次询问,每次询问区间 [l,r] 的数字之和是多少.

Input

第一行两个整数 N,Q.
接下来一行 N 个数字,表示序列的初始值是多少.
接下来 Q 行,每行两个整数 l , r.

Output

输出 Q 行,每行一个整数,代表对应区间的元素之和.

Sample Input

5 2
1 2 3 4 5
1 3
3 5

Copy

Sample Output

6
12

Copy

Hint

0<=N,Q<=100000,a[i]<=1e9
常数尽量小吧,要不很容易被卡.

本题不能用cin、cout输入输出,否则会超时。即使使用下面的两条语句优化加速后也会超时:

ios::sync_with_stdio(false); 
  cin.tie(0);cout.tie(0);

#include<iostream>
#include<cstdio>
#define N 100005
long long a[N];
int main()
{
	int n,q;
	scanf("%d%d",&n,&q);
	long long x;
	for(int i = 1; i <= n; ++i)
	{
		scanf("%lld",&x);
		a[i]= a[i-1] + x;
	}
	int l,r;
	while(q--)
	{
		scanf("%d%d",&l,&r);
		//cout << a[r]-a[l-1] << endl;
		printf("%lld\n",a[r]-a[l-1]);
	}
	return 0;
}
#include<iostream>
#include<cstdio>
#define N 100005
long long a[N];
int main()
{
	int n,q;
	scanf("%d%d",&n,&q);
	//long long x;
	for(int i = 1; i <= n; ++i)
	{
		scanf("%lld",&a[i]);
		a[i]= a[i-1] + a[i];
	}
	int l,r;
	while(q--)
	{
		scanf("%d%d",&l,&r);
		//cout << a[r]-a[l-1] << endl;
		printf("%lld\n",a[r]-a[l-1]);
	}
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章