边缘元素之和等价于「全部元素之和 − 内部子矩阵之和」,直接读入累加即可。
OJ: roj
题目 ID: 1121
难度:入门
标签:入门数组矩阵
创建: 2026-09-29 19:50
更新: 2026-10-05 02:32
题目描述
给定 3 3 / 3 4 1 / 3 7 1 / 2 0 1,样例输出 15。
思路
读入时累加全部元素得到
参考代码
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 20:01
import sys
def solve() -> None:
data = iter(map(int, sys.stdin.buffer.read().split()))
m, n = next(data), next(data)
grid = list(data) # 剩下全部 token:行优先展平的 m 行 n 列元素
# 边缘和 = 全部元素和 - 内部元素和。内部格子是第 1..m-2 行(0 起编号)各去掉
# 首尾两列后的连续段;m <= 2 或 n <= 2 时这段为空,减法自动退化成整矩阵求和。
inner_sum = sum(
sum(grid[r * n + 1: (r + 1) * n - 1]) # 第 r 行:跳过第 1 列,切到最后 1 列之前
for r in range(1, m - 1) # 内部行,0 起编号的首尾两行不在其中
)
print(sum(grid) - inner_sum)
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:31
* update_at: 2026-10-05 02:31
*/
#include <iostream>
using namespace std;
typedef long long ll;
const int MAXN = 105;
int a[MAXN][MAXN]; // a[i][j] 表示第 i 行第 j 列的元素(1 起编号)
int m, n;
// 思路:边缘 = 全部 − 内部。直接读入时累加所有元素,再单独把
// 内部子矩阵(第 2..m-1 行、第 2..n-1 列)累加一次,相减即得。
// m ≤ 2 或 n ≤ 2 时内部区域为空,自然退化为整矩阵求和。
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
if (!(cin >> m >> n)) return 0;
ll total = 0, inner = 0;
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
cin >> a[i][j];
total += a[i][j];
// 内部行 i∈[2,m-1] 且内部列 j∈[2,n-1]
if (i >= 2 && i <= m - 1 && j >= 2 && j <= n - 1)
inner += a[i][j];
}
}
cout << total - inner << "\n";
return 0;
}