直接上代码
1 #include<iostream> 2 #include<vector> 3 #include<numeric> 4 5 using namespace std; 6 7 int main(){ 8 int n, left, right; 9 cin >> n; 10 int array[n] = {0}; 11 int sum[n+1] = {0}; 12 13 for (int i = 0; i < n; ++i) { 14 cin >> array[i]; 15 sum[i+1] = sum[i] + array[i]; 16 } 17 18 while (cin>> left >> right) { 19 cout << sum[right+1] - sum[left] << endl; 20 } 21 22 return 0; 23 24 }
这代码就通过了一次,但是后面就开始超时了,真想不明白了
然后又去看了答案,用的scanf做的,上代码
1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 int main() { 5 int n, a, b; 6 cin >> n; 7 vector<int> vec(n); 8 vector<int> p(n); 9 int presum = 0; 10 for (int i = 0; i < n; i++) { 11 scanf("%d", &vec[i]); 12 presum += vec[i]; 13 p[i] = presum; 14 } 15 16 while (~scanf("%d%d", &a, &b)) { 17 int sum; 18 if (a == 0) sum = p[b]; 19 else sum = p[b] - p[a - 1]; 20 printf("%d\n", sum); 21 } 22 }
解释如下:C++ 代码 面对大量数据 读取 输出操作,最好用scanf 和 printf,耗时会小很多
标签:卡码,58,int,sum,cin,区间,array,include,scanf From: https://www.cnblogs.com/EEhome/p/18386355