两个整数逐月模拟:月初领 300 扣预算后判负输出 -月号,整百用 hand / 100 * 100 表达而无需分支,年末 saved * 6 / 5 整数加两成避开浮点。
OJ: roj
题目 ID: 1074
难度:入门
标签:入门模拟python
创建: 2026-09-29 17:30
更新: 2026-10-05 00:10
题目描述
津津每月月初拿到 300 元,实际花销总等于预算。若预计月末手中还多于或恰好 100 元,就把整百的钱存到妈妈那里,年末妈妈加上 20% 归还;若某个月钱不够花,输出该月月号的相反数。
输入 12 行,每行一个小于 350 的非负整数,依次表示 1 到 12 月的预算。输出一个整数:出现钱不够用的第一个月则输出 290 230 280 200 300 170 340 50 90 80 200 60,输出 -7;样例 2 把第 7 月改成 330,输出 1580。
思路
维护手中零钱 hand 与整百存款 saved,逐月执行 hand += 300 - 预算:一旦 hand < 0,当前月就是第一个破产月,输出 -月号 并结束。存款取不回来,所以判负只看 hand;非负时用 saved += hand / 100 * 100; hand %= 100 存整百,余额不足 100 时该式自动为 0。答案 hand + saved * 6 / 5,用整数运算避开 1.2 的浮点误差。
参考代码
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:30
# update_at: 2026-09-29 17:30
import sys
def solve() -> None:
budgets = [int(s) for s in sys.stdin.read().split()] # 1~12 月的预算
hand = 0 # 自己手中的余钱(百元以内)
saved = 0 # 存在妈妈那里的钱(全是整百)
for month, budget in enumerate(budgets, 1):
hand += 300 - budget # 月初领 300,月末恰好花掉预算
if hand < 0: # 这个月入不敷出,计划破产
print(-month)
return
saved += hand // 100 * 100 # 预计月末还有 ≥100,就存整百
hand %= 100
print(hand + saved * 6 // 5) # 年末取回存款并加 20%
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:10
* update_at: 2026-10-05 00:10
*/
#include <cstdio>
typedef long long ll;
ll budget[13]; // budget[i] = 第 i 个月的预算(i 从 1 到 12)
ll hand; // 手中零钱(不足百元的部分)
ll saved; // 存在妈妈那里的钱,始终是整百
int main() {
for (ll month = 1; month <= 12; ++month) {
scanf("%lld", &budget[month]);
}
for (ll month = 1; month <= 12; ++month) {
// 月初领 300 元,实际花销恰好等于预算
hand += 300 - budget[month];
// 钱不够花:这个月就是第一个破产月,直接输出并结束
if (hand < 0) {
printf("%lld\n", -month);
return 0;
}
// 预计月末还有 >=100 就把整百存进妈妈那里;不足百元时该式自动为 0
saved += hand / 100 * 100;
hand %= 100;
}
// 年末妈妈把存款加上 20% 还回来,用整数运算避免浮点误差
printf("%lld\n", hand + saved * 6 / 5);
return 0;
}