a219簡單流程模擬、時間與狀態更新

TOI 2019/03 新手組:大吃大喝

從時間零開始交替購買,當指定食物買不起便停止。

前往題目練習 →回報教學錯誤成功次數 Q:時間 O(Q),C++ 額外空間 O(1)(Python 輸出清單 O(Q))。

這題在學什麼

兩種食物價格為 32、55,初始種類是 K;若錢足夠,先扣款再輸出該次紀錄。

剩餘金額大於 1、等於 1、等於 0 分別使用 dollars、dollar、doesn't have money.。

成功後時間加 M、種類切換;一開始就買不起才輸出 Wayne can't eat and drink.,買過後停止不加其他文字。

Step-by-step animation

大吃大喝・交替購買與精確文句

回報動畫錯誤
步驟 1 / 3

時間 0

先吃 32 元蘋果派,200-32=168。

Apple pie
剩168
時間
0
money
168

Reference solution

回報程式錯誤

完整程式

#include <iostream>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int money, m, k;
    cin >> money >> m >> k;
    int cost[2] = {32, 55}, t = 0;
    bool any = false;
    while (money >= cost[k]) {
        money -= cost[k];
        any = true;
        cout << t << ": Wayne " << (k == 0 ? "eats an Apple pie" : "drinks a Corn soup")
             << ", and now he ";
        if (money == 0)
            cout << "doesn't have money.";
        else
            cout << "has " << money << (money == 1 ? " dollar." : " dollars.");
        cout << '\n';
        t += m;
        k = 1 - k;
    }
    if (!any)
        cout << "Wayne can't eat and drink.\n";
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多