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

TOI 2020/11 新手組:老鷹抓小雞

以編號查出被抓位置,讓老鷹與該小雞互換角色。

前往題目練習 →回報教學錯誤時間 O(N+Q),空間 O(U+N),U=10001(Python 雜湊表期望時間)。

這題在學什麼

小雞陣列記錄隊伍順序,另外用編號到位置的表保存每隻小雞在哪裡。

抓到編號 x 時,將目前老鷹放到 x 的位置,更新其位置;x 變成新老鷹。

刪除 x 的小雞位置紀錄,其餘位置不變,完成 Q 回合後列出陣列。

Step-by-step animation

老鷹抓小雞・位置索引交換

回報動畫錯誤
步驟 1 / 3

抓到 20

初始老鷹 99 站進原本 20 的位置。

10
99
30
40
eagle
20

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    vector<int> a(n), pos(10001, -1);
    for (int i = 0; i < n; i++) {
        cin >> a[i];
        pos[a[i]] = i;
    }
    int eagle, q;
    cin >> eagle >> q;
    while (q--) {
        int x;
        cin >> x;
        int p = pos[x];
        a[p] = eagle;
        pos[eagle] = p;
        pos[x] = -1;
        eagle = x;
    }
    for (int i = 0; i < n; i++)
        cout << (i ? " " : "") << a[i];
    cout << '\n';
}

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

更多