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
Sample Output
6
12
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;
}