a394中等水平碰撞模擬・整件貨物提交

APCS 2022/10:運貨站 (ZeroJudge j123)

逐格將指定形狀向左推,僅在整件進入倉庫時更新占用格。

前往題目練習 →回報教學錯誤時間 O(RC+n(C+1)s),s≤5 為每件格數;模擬空間 O(RC),Python 含輸入暫存共 O(RC+n)。

這題在學什麼

把 A 到 E 寫成題面列出的格子偏移。貨物的列座標永遠是 y 加列偏移,只有外框左端 x 會改變;從 x=C 開始,所有方格都在右側門外。每次檢查 x−1 的全部方格,遇到左牆或已占用格便停止,否則繼續左移。門外的格子不是障礙。

停止的位置就是從右方進入時最先遇到阻擋的位置,不能越過障礙去找更左的空洞。接著檢查每一格是否都在欄 0 到 C−1 內;只要仍有一格在門外,就整件丟棄,不能先寫入部分方格。完整入庫才標記全部格子並扣除空格數。

每次移動檢查的是完整形狀,因此 D、E 的突出部分也會正確碰撞。倉庫只在成功入庫後改變,正好維持『只含先前接受貨物』的不變量。

Step-by-step animation

公開範例一:同一列第二件 B 被丟棄

回報動畫錯誤
步驟 1 / 4

第一件 B 進入第 0 列

寬 3 的 B 從右方移到 x=0,遇左牆停止。

###.
....
....
....
....
空格
17
丟棄
0

Reference solution

回報程式錯誤

完整程式

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

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int R, C, n;
    cin >> R >> C >> n;
    vector<vector<pair<int, int>>> shapes = {
        {{0,0}, {1,0}, {2,0}, {3,0}},
        {{0,0}, {0,1}, {0,2}},
        {{0,0}, {0,1}, {1,0}, {1,1}},
        {{0,2}, {1,0}, {1,1}, {1,2}},
        {{0,1}, {1,0}, {1,1}, {2,0}, {2,1}}
    };
    vector<vector<bool>> used(R, vector<bool>(C, false));
    int empty = R * C, discarded = 0;
    while (n--) {
        char type;
        int y;
        cin >> type >> y;
        const auto& shape = shapes[type - 'A'];
        int x = C;
        while (true) {
            bool blocked = false;
            for (auto [dr, dc] : shape) {
                int col = x - 1 + dc;
                if (col < 0 || (col < C && used[y + dr][col])) {
                    blocked = true;
                    break;
                }
            }
            if (blocked) break;
            --x;
        }
        bool fits = true;
        for (auto [dr, dc] : shape) {
            if (x + dc >= C) fits = false;
        }
        if (!fits) {
            ++discarded;
            continue;
        }
        for (auto [dr, dc] : shape) used[y + dr][x + dc] = true;
        empty -= (int)shape.size();
    }
    cout << empty << ' ' << discarded << '\n';
}

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

更多