a327困難射程單調擴張・免費寶物優先與最大增幅堆
TOI 2022/03 潛力組:射擊遊戲
在可達寶物中先處理不消耗淨發射數者,再選最大射程增幅。
解題思路
寶物依距離平方排序,當射程擴張就把新可達者放入優先佇列。bi=1 的寶物命中後補回一次發射,淨消耗為 0,而且 ci≥0;只要還有一次發射機會,先取這種寶物永遠不會讓後續選擇變差,甚至能開放更多目標。因此堆先按 b 降序,再按 c 降序選擇。
當沒有可達的免費寶物時,每個可選者都消耗一次機會,選 ci 最大者。交換論證:若某最佳策略先選較小增幅,改先選最大者,第一次射程至少一樣大,其餘尚未選的寶物仍可按原序取得;如果原策略之後才選最大者,就交換兩者,直到第二次選取後總射程相同,中途只會更大。每次射擊後重新加入可達目標,不能只把初始可達者排序一次。
Step-by-step animation
公開範例 1:R=1、D=1
步驟 1 / 3
初始可達兩件
(0,−1) 與 (1,0) 距離皆為 1;前者 b=1,優先取。
c1,b1
c5,b0
距離√13未達
- R
- 1
- D
- 1
#include <iostream>
#include <vector>
#include <array>
#include <algorithm>
#include <queue>
#include <utility>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, r;
long long d;
cin >> n >> r >> d;
vector<array<long long, 3>> items(n);
for (auto &v : items) {
long long x, y, c, b;
cin >> x >> y >> c >> b;
v = {x * x + y * y, b, c};
}
sort(items.begin(), items.end());
priority_queue<pair<int, int>> heap;
int next = 0;
while (r > 0) {
while (next < n && items[next][0] <= d * d) {
heap.push({(int)items[next][1], (int)items[next][2]});
++next;
}
if (heap.empty())
break;
auto [b, c] = heap.top();
heap.pop();
d += c;
r += b - 1;
}
cout << d << '\n';
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。