a678中等團隊佇列的兩層 FIFO
CPE:Team Queue (UVa 540)
每次入隊、出隊只更新隊伍順序與隊內順序。
解題思路
同隊成員在整條佇列中總是連成一段:新成員只插在該段尾端,出隊只刪除最前一段的首位。因此不必在大佇列中搜尋隊友,只需維護 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]
#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';
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。