把每次测量压成正常/异常布尔值,一次遍历维护以当前位置结尾的连续段长,逐步取 max 得到最长正常小时数。
OJ: roj
题目 ID: 1076
难度:入门
标签:入门模拟python
创建: 2026-09-29 17:30
更新: 2026-10-05 00:21
题目描述
监护室每小时测一次血压。若收缩压在
思路
每次测量独立判定正常与否,然后求最长连续正常段。遍历一次,正常则当前段长度加一,异常则清零,同时维护最大值。
参考代码
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 17:32
# update_at: 2026-09-29 17:32
import sys
def solve() -> None:
data = iter(map(int, sys.stdin.buffer.read().split()))
n = next(data) # 测量次数(每小时一次)
longest = run = 0 # 最长连续正常小时数 / 当前连续正常小时数
for _ in range(n):
systolic, diastolic = next(data), next(data) # 收缩压、舒张压
# 正常:收缩压 90-140 且舒张压 60-90(都含端点)
is_normal = 90 <= systolic <= 140 and 60 <= diastolic <= 90
run = run + 1 if is_normal else 0 # 一旦异常,当前段清零重数
longest = max(longest, run)
print(longest)
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 00:21
* update_at: 2026-10-05 00:21
*/
#include <iostream>
using namespace std;
typedef long long ll;
ll n; // 测量次数
ll cur_run; // 以当前位置结尾的连续正常段长度
ll ans; // 最长连续正常小时数
// 判断一次测量 (s, d) 是否属于正常血压
bool is_normal(ll s, ll d) {
return 90 <= s && s <= 140 && 60 <= d && d <= 90;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n;
for (ll i = 1; i <= n; ++i) {
ll s, d;
cin >> s >> d;
if (is_normal(s, d)) {
++cur_run; // 正常则当前段延长一格
} else {
cur_run = 0; // 异常则清零
}
if (cur_run > ans) {
ans = cur_run; // 逐步更新最长长度
}
}
cout << ans << '\n';
return 0;
}