C++ アルゴリズムとデータ構造のライブラリ
#include "library/dp/cumulative_sum/cumulative_sum.hpp"A: 1 4 2 8 2 9
S: 0 1 5 7 15 17 26
半開区間 $[l, r)$ の和は、次のように求められる。
$\displaystyle\sum_{j=l}^{r-1} A_j = S_r - S_l$
$O(N)$
vector<long long> S = cumulative_sum(A);
#pragma once
vector<long long> cumulative_sum(const vector<long long> &A) {
int N = A.size();
vector<long long> S(N + 1);
for (int i = 0; i < N; ++i) S[i + 1] = S[i] + A[i];
return S;
}#line 2 "library/dp/cumulative_sum/cumulative_sum.hpp"
vector<long long> cumulative_sum(const vector<long long> &A) {
int N = A.size();
vector<long long> S(N + 1);
for (int i = 0; i < N; ++i) S[i + 1] = S[i] + A[i];
return S;
}