a678中等團隊佇列的兩層 FIFO

CPE:Team Queue (UVa 540)

每次入隊、出隊只更新隊伍順序與隊內順序。

前往題目練習 →回報教學錯誤每組 M 位成員、T 隊、Q 次操作、最大佇列長度 H:建表平均 O(M+T),每次操作平均 O(1),核心總時間 O(M+T+Q),C++ 空間 O(M+T+H)。Python 另保存整份輸入及累積輸出,若其總字元數為 I、L,額外時間與空間 O(I+L);總空間 O(M+T+H+I+L),M、T、H 取各組峰值。雜湊操作採平均成本,輸入輸出字元處理另計。

解題思路

同隊成員在整條佇列中總是連成一段:新成員只插在該段尾端,出隊只刪除最前一段的首位。因此不必在大佇列中搜尋隊友,只需維護 active 佇列記錄非空團隊順序,並為每隊維護一個成員佇列。

ENQUEUE x 時先查 x 的團隊;該隊原本為空才將隊號放到 active 尾端,之後把 x 加入隊內尾端。DEQUEUE 時從 active 首隊取出首位成員,若該隊變空,再把隊號取走。每組 STOP 結束、t=0 結束全部;先印 Scenario #k,每組最後空一行。

Step-by-step animation

示意:隊0含101,102,隊1含201

回報動畫錯誤
步驟 1 / 3

加入 101

隊0首次非空,active=[0]。

隊0:[101]
隊1:[]
active
[0]

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <queue>
#include <string>
#include <unordered_map>
using namespace std;
int main() {
    int t, tc = 0;
    while (cin >> t && t) {
        unordered_map<int, int> team;
        for (int i = 0; i < t; i++) {
            int k, x;
            cin >> k;
            while (k--) {
                cin >> x;
                team[x] = i;
            }
        }
        vector<queue<int>> members(t);
        queue<int> active;
        string command;
        cout << "Scenario #" << ++tc << '\n';
        while (cin >> command && command != "STOP") {
            if (command == "ENQUEUE") {
                int x;
                cin >> x;
                int id = team[x];
                if (members[id].empty())
                    active.push(id);
                members[id].push(x);
            } else {
                int id = active.front();
                cout << members[id].front() << '\n';
                members[id].pop();
                if (members[id].empty())
                    active.pop();
            }
        }
        cout << '\n';
    }
}

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

更多