通过一次遍历找出二维网格中所有整数的最大值与最小值,计算两者之差即为玉米杆高度差。
OJ: roj
题目 ID: 1672
难度:入门
标签:模拟极值
创建: 2026-10-01 01:23
更新: 2026-10-06 01:45
题目描述
给定
思路
遍历所有高度,维护最大值与最小值,两者相减即为答案。
参考代码
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-07-05 21:47
# update_at: 2026-10-04 10:22
import sys
def solve() -> None:
data = iter(map(int, sys.stdin.buffer.read().split()))
# 第一行包含两个整数 m 和 n,表示矩阵的行数与列数
m, n = next(data), next(data)
heights = [next(data) for _ in range(m * n)]
# 玉米杆高度差 = 最大高度 - 最小高度
diff = max(heights) - min(heights)
print(diff)
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-06 01:45
* update_at: 2026-10-06 01:45
*/
#include <iostream>
#include <climits>
using namespace std;
typedef long long ll;
ll mx = LLONG_MIN; // 当前最大值
ll mn = LLONG_MAX; // 当前最小值
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
ll m, n;
cin >> m >> n;
for (ll i = 0; i < m; ++i) {
for (ll j = 0; j < n; ++j) {
ll x;
cin >> x;
if (x > mx) mx = x;
if (x < mn) mn = x;
}
}
cout << mx - mn << "\n";
return 0;
}