题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=108
一开始竟然用的vector保存的第i项到第j项的和,果断爆掉了内存呢,我真的是醉了。。
用一个数组保存前K项的和,例如 b[k] = a[1] + ... + a[k] 的和,然后就不说了,都是泪。。(用时244MS)
代码:
#include <cstdio> #include <cstring> using namespace std; const int maxn = 1e6; int b[maxn + 5]; int a[maxn + 5]; int main() { int n,m; scanf("%d%d",&n,&m); //printf("%d %d\n",n,m); for(int i = 1;i <= n;++i){ scanf("%d",&a[i]); } for(int i = 1;i <= n;++i) { b[i] = b[i - 1] + a[i]; } while(m--) { int c,d; scanf("%d%d",&c,&d); if(c > d) { int t = c; c = d; d = t; } printf("%d\n",b[d] - b[c] + a[c]); } return 0; }
还有一种用树状数组的方法,用时316MS
代码:
#include <cstdio> const int maxn = 1e6; int a[maxn + 5]; int c[maxn + 5]; int n,m; void add(int k,int num) { while(k <= n) { c[k] += num; k += k & -k; } } int query(int k) { int sum = 0; while(k) { sum += c[k]; k -= k & -k; } return sum; } int main() { scanf("%d%d",&n,&m); for(int i = 1;i <= n;++i){ scanf("%d",&a[i]); add(i,a[i]); } while(m--) { int x,y; scanf("%d%d",&x,&y); if(x > y) { int t = x; x = y; y = t; } printf("%d\n",query(y) - query(x - 1)); } return 0; }