不高兴的津津

GitHub跳转原题关系图返回列表

遍历七天课程总时长,仅在出现更长时更新最不高兴的最早日期。

OJ: noi_openjudge

题目 ID: ch0109-03

难度:入门

标签:模拟最值python

日期: 2026-07-30 23:01

题意

每天课程超过八小时会不高兴,输出课程总时长最大的最早一天;没有超过八小时则输出 00

思路

初始最长时长设为 88。仅当新时长严格更大才更新日期,因此总时长并列时会保留更早的日期。

代码

cpp
#include <cstdio>

int main(){
    int a,b;
    
    int c =0;
    int max = -1;
    int i;
    for(i=1;i<=7;i++){
        scanf("%d%d",&a,&b);

        if( a+b > 8){
            if( a+b -8 > max){
                max= a+b-8;
                c=i;
            }
        }
    }
	printf("%d",c);
    return 0;
}

复杂度

固定七天,时间和额外空间复杂度均为 O(1)O(1)

总结

需要保留首次最值时,更新条件使用严格比较。

Python代码

python
worst_day = 0
longest_time = 8

for day in range(1, 8):
    school_time, extra_time = map(int, input().split())
    total_time = school_time + extra_time
    if total_time > longest_time:
        longest_time = total_time
        worst_day = day

print(worst_day)

C++代码

cpp
#include <cstdio>

int main(){
    int a,b;
    
    int c =0;
    int max = -1;
    int i;
    for(i=1;i<=7;i++){
        scanf("%d%d",&a,&b);

        if( a+b > 8){
            if( a+b -8 > max){
                max= a+b-8;
                c=i;
            }
        }
    }
	printf("%d",c);
    return 0;
}