ホーム AtCoder Typical 90 004 — Cross Sum (2)
記事
キャンセル

AtCoder Typical 90 004 — Cross Sum (2)

問題リンク

各マスについて、そのマスと同じ行および列にある値の合計を出力します。各行の合計と各列の合計を一度ずつ計算し、それらを使ってすべてのマスの答えを求めます。対象のマス自身は行の合計と列の合計の両方に含まれるため、一度引いて重複分を取り除きます。

rowSum[i] + colSum[j] - grid[i][j]

合計が int の範囲を超えても正しく扱えるよう、値と合計には long を使います。グリッドの読み込みと合計の計算にかかる時間計算量は O(HW) です。グリッドに O(HW)、行・列の合計配列に追加で O(H + W) の空間を使います。

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.io.*;
import java.util.*;

public class Main {
  static class FastScanner {
    private final InputStream input;
    private final byte[] buffer = new byte[1 << 16];
    private int length = 0;
    private int pointer = 0;

    FastScanner(InputStream input) {
      this.input = input;
    }

    private int read() throws IOException {
      if (pointer == length) {
        length = input.read(buffer);
        pointer = 0;
        if (length == -1) return -1;
      }
      return buffer[pointer++];
    }

    long nextLong() throws IOException {
      int c;
      do {
        c = read();
      } while (c <= ' ' && c != -1);

      long value = 0;
      while (c > ' ') {
        value = value * 10 + c - '0';
        c = read();
      }
      return value;
    }
  }

  public static void main(String[] args) throws IOException {
    FastScanner input = new FastScanner(System.in);
    int h = (int) input.nextLong();
    int w = (int) input.nextLong();
    long[][] grid = new long[h][w];
    long[] rowSum = new long[h];
    long[] colSum = new long[w];

    for (int i = 0; i < h; i++) {
      for (int j = 0; j < w; j++) {
        grid[i][j] = input.nextLong();
        rowSum[i] += grid[i][j];
        colSum[j] += grid[i][j];
      }
    }

    StringBuilder output = new StringBuilder();
    for (int i = 0; i < h; i++) {
      for (int j = 0; j < w; j++) {
        if (j > 0) output.append(' ');
        output.append(rowSum[i] + colSum[j] - grid[i][j]);
      }
      output.append('\n');
    }
    System.out.print(output);
  }
}
この記事は著者により CC BY 4.0 ライセンスで公開されています。