Question description
There is a grid with rows and columns. The cell at the -th row from the top and -th column from the left, denoted as , contains the integer .
For all cells where and , find the following value:
- The sum of integers written in the cells that are in the same row or the same column as cell (including the cell itself).Constraints
Input
The input is given in the following format from standard input:
Output
Let be the sum of integers written in the cells that are in the same row or the same column as cell (including the cell itself). Output the values in the following format:
Examples Input example
4 4
3 1 4 1
5 9 2 6
5 3 5 8
9 7 9 3
Output example
28 28 25 26
39 33 40 34
38 38 36 31
41 41 39 43
The sum of integers written in cells that are in the same row or column as cell is as follows:
Approach
- Create a matrix .
- Calculate row_sum, where `row_sum[i]$ is the sum of the -th row.
- Calculate col_sum, where `col_sum[j]$ is the sum of the -th column.
- Print the result of cell , which is row_sum[i] + col_sum[j] - M[i][j].
Complexity Analysis
- time complexity :
Solution
#include <iostream>
#include <vector>
using namespace std;
int main(){
int H, W;
cin >> H >> W;
vector<vector<int>> M(H, vector<int>(W, 0));
vector<int> row_sum(H, 0), col_sum(W, 0);
for (int i = 0; i < H; i++) {
int sum = 0;
for (int j = 0; j < W; j++) {
cin >> M[i][j];
sum += M[i][j];
}
row_sum[i] = sum;
}
for (int j = 0; j < W; j++) {
int sum = 0;
for (int i = 0; i < H; i++) {
sum += M[i][j];
}
col_sum[j] = sum;
}
for (int i = 0; i < H; i++) {
for (int j = 0; j < W; j++) {
cout << row_sum[i] + col_sum[j] - M[i][j];
if (j != W - 1) cout << " ";
}
cout << endl;
}
return 0;
}
Reference
[1] 競プロ典型 90 問
[2] 004 - Cross Sum(★2)