题解:P12166 [蓝桥杯 2025 省 C/Java A/研究生组] 冷热数据队列
题目大意
有四个操作:
- 若
p 不在队列q 中(即既不在q_1 中,也不在q_2 中),则加载数据页p ,并插入到q_2 的首部。 - 若
p 已经在队列q 中,则将p 移动至q_1 首部。 - 当
q_1 或q_2 队列容量不足时,会将其尾部的数据页淘汰出去。 - 当
q_1 已满,但q_2 未满时,从q_1 中淘汰出的数据页会移动到q_2 首部。
题目思路
直接用链表大模拟。
代码
#include<bits/stdc++.h>
using namespace std;
int n1,n2,m;
list<int> q1,q2;
bool b[1000005];
pair<int,list<int>::iterator> p[1000005];
int main(){
scanf("%d%d%d",&n1,&n2,&m);
while(m--){
int x;
scanf("%d",&x);
if(!b[x]){
q2.push_front(x);
b[x]=1;
p[x]={2,q2.begin()};
}
else{
auto it=p[x];
if(it.first==1)
q1.erase(it.second);
else q2.erase(it.second);
q1.push_front(x);
p[x]={1,q1.begin()};
}
if(q1.size()>n1){
int t=*q1.rbegin();
q2.push_front(t);
p[t]={2,q2.begin()};
q1.pop_back();
}
if(q2.size()>n2){
int t=*q2.rbegin();
b[t]=0;
q2.pop_back();
}
}
for(auto i:q1)
cout<<i<<' ';
cout<<endl;
for(auto i:q2)
cout<<i<<' ';
}