求和

【题目描述】
给你一个长为k的序列,还有n个询问,对于每个询问[a,b]输出s[a]+s[a+1]……+s[b]的和,保证a<=b,答案不会超过maxlongint
【输入格式】
第一行:k,n
第二行:连续的k个数,表示s[1],s[2]……s[k]
剩下的n行,每行2个数,表示一次询问
【输出格式】
对每一个询问,输出一行表示答案
【输入样例】
10 3
1 2 3 4 5 6 7 8 9 0
1 2
3 6
7 9
【输出样例】
3
18
24
【数据范围】
0%的数据 n<=0,k<=0
100%的数据 k<=100000,n<=10000
代码

#include<bits/stdc++.h>
using namespace std;
int a[100001];
int main(){
	freopen("query.in", "r", stdin);
	freopen("query.out", "w", stdout);
	int n, m;
	cin >> n >> m;
	for(int i = 1; i <= n; i++)scanf("%d", &a[i]);
	for(int i = 1; i <= m; i++){
		int x, y, ans = 0;
		scanf("%d%d", &x, &y);
		if(x % 2 != y % 2)x++, ans += a[x-1];
		if(x == y){
			printf("%d
", a[x-1] + a[y]);
			continue;
		}
		if(y - x == 1){
			printf("%d
", a[x-1] + a[x] + a[x+1]);
			continue;
		}
		for(int j = x; j <= y - 2; j+=2)ans += a[j] + a[j+1];
		ans += a[y];
		printf("%d
", ans);
	}
	return 0;
}
原文地址:https://www.cnblogs.com/LJA001162/p/13392011.html