逐年比较累计工资与当年房价,找出二十年内最早可购房年份。
OJ: noi_openjudge
题目 ID: ch0105-16
难度:普及-
标签:模拟循环python
日期: 2026-07-30 23:01
题意
初始房价为 200 万,每年上涨
思路
第 year 年开始时已攒下 salary * year,当前房价从 200 开始,若买不起再乘增长因子更新到下一年。按年从 1 到 20 模拟,第一次满足条件就是最早答案。
代码
Python代码
python
salary, annual_growth = map(int, input().split())
price = 200.0
for year in range(1, 21):
if salary * year >= price:
print(year)
break
price *= 1 + annual_growth / 100
else:
print("Impossible")C++代码
cpp
#include <cstdio>
int main(){
int n,k;
scanf("%d%d",&n,&k);
int i;
double lilv = 1+k*0.01;
double fangjia= 200;
for (i=1;i<=20;i++){
if( n*i*1.0 >= fangjia){
break;
}
fangjia = fangjia * lilv;
}
if( i <= 20){
printf("%d",i);
}
else
printf("Impossible");
return 0;
}复杂度
最多模拟 20 年,时间复杂度和额外空间复杂度均为
总结
“最早第几年”适合按时间顺序模拟;关键是统一工资累计和房价更新的时序。