2017.7.20. 前缀和

来源:互联网 发布:linux拷贝隐藏文件 编辑:程序博客网 时间:2024/05/16 14:48

前缀和

适用题型:
1.查询区间和或点
2.数据静态存储,改完再查

样题:

给出一个含有n个整数的数列a,并且有m次询问,每次询问数列在区间[l,r]内的和,即求a[l]+a[l+1]+……+a[r]的值。
Input
第一行为一个整数 T (1 ≤ T ≤ 50),表示共有T组输入数据;

对于每组数据,第一行是两个正整数 n,m (1 ≤ n ≤ 100000,1 ≤ m≤ 1000)分别代表数列长度和询问次数;
第二行行有 n 个正整数,第 i 个数表示数列元素 a[i] (1 ≤ a[i] ≤ 10^9)的值;
接下来 m 行,每行有两个正整数 l,r (1 ≤ l ≤ r ≤ n),代表询问内容。
Output
每组数据输出 m 行,每行一个数为该次询问的区间和。
保证数据都在64位正整数范围内。
Sample Input
2
5 2
1 2 3 4 5
1 5
3 5
4 1
1 1 1 1
1 2
Sample Output
15
12
2

std.cpp:

#include<iostream>#include<cstdio>#include<cstdlib>#include<cmath>#include<cstring>#include<string>#include<algorithm>using namespace std;  long long ans[1000005];  int n,m,l,r;  int main() {      int T;      cin >> T;      while(T--) {          cin >> n >> m;         int x;          ans[0] = 0;          for(int i=1;i<=n;i++)         {              cin >> x;             ans[i] = ans[i-1] + x;          }          for(int i=1;i<=m;i++)         {              cin >> l >> r ;             cout << ans[r]-ans[l-1] << endl;          }      }       return 0;  }