【深基3.习5】小鱼的航程(改进版) · 教师题解

【深基3.习5】小鱼的航程(改进版)

解题思路

从起始周几开始逐日枚举;周一至周五累加 250,周末跳过,再按 1~7 循环推进星期。

正确性说明

循环每次对应一天,且仅工作日贡献距离。遍历 n 天后累加的就是所有游泳日总距离。

易错点

起始当天算第一天;星期天过后回到星期一。

复杂度

时间 O(n),空间 O(1)。

参考代码(C++11)

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int x, n;
    cin >> x >> n;
    long long ans = 0;
    for (int i = 0; i < n; i++) {
        if (x <= 5)
            ans += 250;
        x = x % 7 + 1;
    }
    cout << ans << "\n";
    return 0;
}
返回题目