a329困難碰撞交換身分・第 M 個離開時間
TOI 2022/12 潛力組:螞蟻暗號
把相撞掉頭視為穿越,直接求停止時間及仍被占用的字元位置。
解題思路
兩隻等速螞蟻相撞後交換方向,若忽略身分,等價於兩者直接穿越。題目只問哪些字元位置有螞蟻,不問身分,因此可以讓每隻沿初始方向直走。向左離開時間為 p,向右為 K+1−p;第 M 小的離開時間就是停止時刻,同時抵達邊界者全部算離開。
時間都是 1..K 的整數,可用計數陣列找第 M 小,不必排序。到停止時間 t 時,計算每隻幽靈螞蟻的位置 p±t,僅保留 1..K。把位置記在布林陣列,最後由左至右讀出紙帶字元;同一位置可能有兩隻正在相撞,但該字元只列一次,這也符合範例 4 的 Me,而不是 MMe。
Step-by-step animation
公開範例 4:K=16,螞蟻 16R、5R、7L、13L
步驟 1 / 3
離開時間
忽略碰撞後,四隻分別在 1、12、7、13 時離開。
16R:t1
5R:t12
7L:t7
13L:t13
- M
- 1
- 停止t
- 1
#include <iostream>
#include <vector>
#include <string>
#include <utility>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int k, n, m;
string text;
cin >> k >> text >> n >> m;
vector<pair<int, int>> ants(n);
vector<int> exits(k + 1);
for (auto &[p, d] : ants) {
cin >> p >> d;
++exits[d ? k + 1 - p : p];
}
int time = 0, count = 0;
while (count < m) {
++time;
count += exits[time];
}
vector<unsigned char> occupied(k + 1);
for (auto [p, d] : ants) {
int q = p + (d ? time : -time);
if (q >= 1 && q <= k)
occupied[q] = 1;
}
for (int p = 1; p <= k; ++p)
if (occupied[p])
cout << text[p - 1];
cout << '\n';
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。