ホーム BOJ 11659 - 区間和を求める 4
記事
キャンセル

BOJ 11659 - 区間和を求める 4

BOJ 11659: 区間和を求める 4

配列の累積和配列を作る。prefix[0] = 0とし、prefix[i + 1] = prefix[i] + value[i]で定義する。入力の位置は1始まりで、両端を含む区間[a, b]の合計はprefix[b] - prefix[a - 1]となる。この式で累積和配列のインデックスを使うことで、入力位置とJavaの0始まり配列インデックスの違いを扱える。

累積和配列の構築にはO(N)時間がかかり、M個の各クエリにはO(1)時間で答えられる。したがって、全体の時間計算量はO(N + M)、空間計算量はO(N)である。BufferedReaderとStringTokenizerを使い、空白や改行の位置に依存せずトークンを読み込み、StringBuilderに答えをまとめて出力する。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
  private static BufferedReader reader =
      new BufferedReader(new InputStreamReader(System.in));
  private static StringTokenizer tokenizer;

  private static int nextInt() throws IOException {
    while (tokenizer == null || !tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine());
    }
    return Integer.parseInt(tokenizer.nextToken());
  }

  public static void main(String[] args) throws IOException {
    int n = nextInt();
    int m = nextInt();
    int[] prefix = new int[n + 1];

    for (int i = 0; i < n; i++) {
      prefix[i + 1] = prefix[i] + nextInt();
    }

    StringBuilder output = new StringBuilder();
    for (int i = 0; i < m; i++) {
      int a = nextInt();
      int b = nextInt();
      output.append(prefix[b] - prefix[a - 1]).append('\n');
    }
    System.out.print(output);
  }
}
この記事は著者により CC BY 4.0 ライセンスで公開されています。