题解:P10647 [NordicOI 2023] Ice Cream Machines
P10647 [NordicOI 2023] Ice Cream Machines 题解
前置知识:贪心、大根堆。
题目大意:
有
思路:
贪心核心思路:
机器占满且无与当前口味相同的口味时,使用下一次出现位置最远的口味,减少后续清洗。
证明:
假设当前必须淘汰一种口味,分两种选择:
- 删下次最远的口味
A 。 - 删另一个更早出现的口味
B 。
选择将
选择将
因此删最远口味能减少后续清洗次数,贪心策略最优。
实现过程:
-
记录每种口味上一次出现的位置与下一次出现的位置,没有则标记为
n + 1 。 -
遍历每一位顾客:
第一种:该口味已在机器中,把当前位置对应的下次位置丢入大根堆,跳过。
第二种:该口味不在机器,清洗计数
+ 1 ;机器已满则弹出堆顶(下次出现最远的口味)并移出机器,将当前口味入堆,标记放入机器,占用机器数+ 1 。 -
输出答案。
AC代码
#include<bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int n,m,k,ans,jqcnt;
int a[N];
int nex[N];
int gs[N];
bool bh[N];
priority_queue<pair<int,int>> v;
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n >> m >> k;
for(int i = 1; i <= n; i++) nex[i] = n + 1;
for(int i = 1; i <= n; i++){
cin >> a[i];
int x = a[i];
nex[gs[x]] = i;
gs[x] = i;
}
for(int i = 1; i <= n; i++){
int x = a[i];
if(bh[x]){
v.push({nex[i],x});
continue;
}
ans++;
if(jqcnt == k){
int del = v.top().second;
v.pop();
bh[del] = 0;
jqcnt--;
}
v.push({nex[i],x});
bh[x] = 1;
jqcnt++;
}
cout << ans;
return 0;
}