a431中等規則模擬・跑者狀態

APCS 2016/10:棒球遊戲 (ZeroJudge c297)

依打序取用每人的下一筆紀錄,逐次更新壘包、出局數與得分。

前往題目練習 →回報教學錯誤設實際打席數為 T:時間 O(T),額外狀態 O(1);輸入紀錄最多 45 筆,儲存空間 O(45)。

這題在學什麼

九位打者輪流上場,因此需要目前打者編號,以及每位打者已使用幾筆紀錄。三個壘包各記錄是否有人;得分與出局數則分開累計。開始時空壘,每人的紀錄指標都是 0。

安打前進 h 壘時,先把舊跑者搬到全新的壘包陣列。舊陣列索引 i 的跑者會到 i+h;若超過第三個壘包便得分。打者另從本壘前進 h 壘,全壘打時直接得分。使用新陣列可保證每位跑者只移動一次。

FO、GO、SO 只增加一次出局,不移動原有跑者;累積出局數為 3 的倍數時清空壘包。每次事件後的狀態都符合規則,因此在第 b 次出局後立即停止,就得到要求的總分,不會多算下一位打者。

Step-by-step animation

示意打席:1B、2B、HR、SO、FO、GO,b=3

回報動畫錯誤
步驟 1 / 4

一壘打

第一位打者停在一壘,尚未得分。

一壘:有人
二壘:空
三壘:空
得分
0
出局
0

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <string>
#include <vector>
#include <array>
using namespace std;

int main() {
    vector<vector<string>> records(9);
    for (auto &row : records) {
        int count;
        cin >> count;
        row.resize(count);
        for (string &event : row) cin >> event;
    }
    int target;
    cin >> target;
    array<int, 9> used{};
    array<int, 3> bases{};
    int batter = 0, outs = 0, score = 0;
    while (outs < target) {
        string event = records[batter][used[batter]++];
        int hit = 0;
        if (event == "1B") hit = 1;
        else if (event == "2B") hit = 2;
        else if (event == "3B") hit = 3;
        else if (event == "HR") hit = 4;
        if (hit == 0) {
            ++outs;
            if (outs % 3 == 0) bases.fill(0);
        } else {
            array<int, 3> next{};
            for (int i = 0; i < 3; ++i) {
                if (!bases[i]) continue;
                if (i + hit >= 3) ++score;
                else next[i + hit] = 1;
            }
            if (hit == 4) ++score;
            else next[hit - 1] = 1;
            bases = next;
        }
        batter = (batter + 1) % 9;
    }
    cout << score << '\n';
}

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

更多