逐行读入两个矩阵,用双重循环对应位置相加后输出,时间复杂度 O(nm)。
OJ: roj
题目 ID: 1124
难度:入门
标签:入门输入输出python
创建: 2026-09-29 19:50
更新: 2026-10-05 02:40
题目描述
输入两个 2 4 6 / 5 7 9 / 8 10 12。
思路
按行读入两个矩阵,用双重循环逐位相加后输出,时间复杂度
参考代码
Python 版:
python
#!/usr/bin/env python3
# Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
# rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
# rainboy的学习导航网站: https://idx.roj.ac.cn
# create_at: 2026-09-29 19:50
# update_at: 2026-09-29 19:50
import sys
def solve() -> None:
data = iter(map(int, sys.stdin.buffer.read().split()))
n, m = next(data), next(data) # 行数、列数
rows_a = [[next(data) for _ in range(m)] for _ in range(n)] # 矩阵 A 的 n 行
rows_b = [[next(data) for _ in range(m)] for _ in range(n)] # 矩阵 B 的 n 行
# 逐行 zip 出对应元素对,逐元素相加后按空格拼接
out = [
' '.join(map(str, (x + y for x, y in zip(row_a, row_b)))) # 同一行同一列相加
for row_a, row_b in zip(rows_a, rows_b)
]
print('\n'.join(out))
if __name__ == "__main__":
solve()C++ 版(同一算法):
cpp
/**
* Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
* rbook: -> https://rbook.roj.ac.cn https://rbook2.roj.ac.cn
* rainboy的学习导航网站: https://idx.roj.ac.cn
* create_at: 2026-10-05 02:40
* update_at: 2026-10-05 02:40
*/
#include <iostream>
using namespace std;
typedef long long ll;
const int MAXN = 105; // 矩阵最大行数/列数
ll a[MAXN][MAXN]; // 矩阵 A
ll b[MAXN][MAXN]; // 矩阵 B
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m; // 行数、列数
cin >> n >> m;
for (int i = 1; i <= n; i++) // 读入矩阵 A
for (int j = 1; j <= m; j++)
cin >> a[i][j];
for (int i = 1; i <= n; i++) // 读入矩阵 B
for (int j = 1; j <= m; j++)
cin >> b[i][j];
for (int i = 1; i <= n; i++) { // 逐位相加并输出
for (int j = 1; j <= m; j++) {
if (j > 1) cout << ' ';
cout << a[i][j] + b[i][j];
}
cout << '\n';
}
return 0;
}