跳到正文

题解

题解:P12166 [蓝桥杯 2025 省 C/Java A/研究生组] 冷热数据队列

lkk1030约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年8月4日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 2 分钟
获赞
1
题目
P12166

版本

  1. v1当前

题目大意

有四个操作:

  1. 若 pp 不在队列 qq 中(即既不在 q1q_1 中,也不在 q2q_2 中),则加载数据页 pp,并插入到 q2q_2 的首部。
  2. 若 pp 已经在队列 qq 中,则将 pp 移动至 q1q_1 首部。
  3. 当 q1q_1 或 q2q_2 队列容量不足时,会将其尾部的数据页淘汰出去。
  4. 当 q1q_1 已满,但 q2q_2 未满时,从 q1q_1 中淘汰出的数据页会移动到 q2q_2 首部。

题目思路

直接用链表大模拟。

代码

C++
#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<<' ';
}
原文