serna37's Library

Logo

C++ アルゴリズムとデータ構造のライブラリ

View the Project on GitHub serna37/library-cpp

:heavy_check_mark: 累積和
(library/dp/cumulative_sum/cumulative_sum.hpp)

累積和

できること

半開区間 $[l, r)$ の和は、次のように求められる。

$\displaystyle\sum_{j=l}^{r-1} A_j = S_r - S_l$

計算量

$O(N)$

使い方

vector<long long> S = cumulative_sum(A);

Verified with

Code

#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;
}
Back to top page