1 条题解

  • 0
    @ 2026-11-3 21:03:39

    思路

    题意:给定同一天内的开始时刻 (h1,m1,s1)(h_1,m_1,s_1) 和结束时刻 (h2,m2,s2)(h_2,m_2,s_2),结束时刻不早于开始时刻,求两者相差多少秒。

    统一换算成「从 00 时 00 分 00 秒起经过的秒数」再相减:

    • 开始时刻 A=3600h1+60m1+s1A = 3600h_1 + 60m_1 + s_1;
    • 结束时刻 B=3600h2+60m2+s2B = 3600h_2 + 60m_2 + s_2;
    • 答案就是 B−AB - A。

    因为两个时刻在同一天内、且结束不早于开始,所以差值一定非负,不需要考虑跨天补加 8640086400 的情况。

    正确性:换算函数是时刻到秒数的一一映射,且保序,因此 B−AB-A 恰好等于两个时刻之间经过的秒数,与「先算时分秒差再进位」的结果一致。

    复杂度:时间 O(1)O(1),空间 O(1)O(1)。

    代码

    #include <bits/stdc++.h>
    using namespace std;
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
    
        int h1, m1, s1, h2, m2, s2;
    
        // 把时刻统一换算为从 0 点起经过的秒数
        long long a = h1 * 3600LL + m1 * 60LL + s1;
        long long b = h2 * 3600LL + m2 * 60LL + s2;
    
        // 结束时刻不早于开始时刻,差值一定非负
        cout << b - a << '\n';
        return 0;
    }
    
    • 1

    信息

    ID
    82
    时间
    1000ms
    内存
    256MiB
    难度
    1
    标签
    递交数
    26
    已通过
    22
    上传者