题解:P10647 [NordicOI 2023] Ice Cream Machines
stripe_python · · 题解
这是我一个月前做的题,现在才补题解,训练效率拉完了。
P10647 [NordicOI 2023] Ice Cream Machines
给出
n,m,k 和长为n 值域[1,m] 的序列a_i 。初始有序列b_1,b_2,\cdots,b_k 且b_i=-1 。对于每个
i=1,2,\cdots,n ,你需要依次进行决策,选择一个j \in [1,k] ,若b_j \ne a_i 则产生1 的代价,并将b_j \gets a_i 。最小化代价并输出。
:::::success[题解]{open}
如果要在线决策的话是不可能最优的,这启示我们分析离线信息。
若
我们的贪心策略是,丢掉在当前
直接模拟可以做到
:::::
:::::info[代码]
const int N = 2e5 + 5;
int n, m, k, a[N], nxt[N], pos[N];
heap<int> q;
heap<int>::point_iterator it[N];
void _main() {
cin >> n >> m >> k;
for (int i = 1; i <= n; i++) cin >> a[i];
fill(pos + 1, pos + m + 1, n + 1);
for (int i = n; i >= 1; i--) nxt[i] = pos[a[i]], pos[a[i]] = i;
int res = 0;
for (int i = 0; i <= m; i++) it[i] = nullptr;
for (int i = 1; i <= n; i++) {
if (it[a[i]] != nullptr) {
q.modify(it[a[i]], nxt[i]);
continue;
}
if ((int)q.size() == k) {
int x = q.top(); q.pop();
it[a[x]] = nullptr;
}
it[a[i]] = q.push(nxt[i]), res++;
}
cout << res;
}
:::::