Home AtCoder. 004 Cross Sum(2)
Post
Cancel

AtCoder. 004 Cross Sum(2)

Problem link

For every cell, output the sum of all values in its row and column. Compute each row sum and column sum once, then combine them for every cell. The cell itself is included in both totals, so subtract it once to count it only once:

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

The values and their sums use long so that large totals do not overflow int. The algorithm takes O(HW) time to read the grid and compute the sums, and O(HW) space for the grid (plus O(H + W) for the sums).

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);
  }
}
This post is licensed under CC BY 4.0 by the author.

Buy me a coffee