4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Atcoderで累積和が出てきたのでこれを機にちょっと勉強する

Last updated at Posted at 2019-11-24

累積和とは

サイズNの配列があって、ある区間iからjまでの和$(0<=i<j<=N)$を爆速で取り出すことができるアルゴリズム。

すでに先人達が多くの解説記事を上げているので、詳細な解説はここでは書かない。
(個人的にはけんちょんさんの記事がわかりやすかった)
累積和を何も考えずに書けるようにする!

Pythonで累積和を実装する

脳筋実装すればこうなる。

# 1~10のリスト
a = [1,2,3,4,5,6,7,8,9,10]

# 累積和用リスト
s = [0] * 10

s[0] = a[0]

for i in range(1, 10):
        s[i] = s[i-1] + a[i]
print(s) # [1, 3, 6, 10, 15, 21, 28, 36, 45, 55]

例えば、インデックスが3〜7の区間の和を取りたければ7までの和2までの和で求めることができる。

print(s[6] - s[1]) #25

こういった配列sを作る方法は上に上げた脳筋forループの他にもいくつかあるが、pythonを使う上で一番早いのはおそらくNumpy.cumsumである。

速度については下記記事で検証されているので、気になる方はどうぞ。
リストから和のリストを得る(累積和)

cumsumの使い方は↓

import numpy as np
# 1~10のリスト
a = [1,2,3,4,5,6,7,8,9,10]

# 累積和用リスト
s = np.cumsum(a)
print(s) # [ 1  3  6 10 15 21 28 36 45 55]

Pythonは便利なライブラリが多くていいですね。

4
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?