文章目录
- [1. 【模板】队列](#1. 【模板】队列)
- [2. 机器翻译](#2. 机器翻译)
- [3. 海港(这道题不错!)](#3. 海港(这道题不错!))
1. 【模板】队列
https://www.luogu.com.cn/problem/B3616

直接按照静态队列的实现方式进行模拟即可!
cpp
#include<bits/stdc++.h>
using namespace std;
const int N = 10010;
int h,t;
int q[N];
int size()
{
return t-h;
}
int main()
{
int n;
cin>>n;
while(n--)
{
int num;
cin>>num;
if(num==1)
{
int x;
cin>>x;
q[++t]=x;
}
else if(num==2)
{
if(size()==0)
{
cout<<"ERR_CANNOT_POP"<<endl;
}
else
{
h++;
}
}
else if(num==3)
{
if(size()==0)
{
cout<<"ERR_CANNOT_QUERY"<<endl;
}
else
{
cout<<q[h+1]<<endl;
}
}
else
{
cout<<size()<<endl;
}
}
return 0;
}
2. 机器翻译
https://www.luogu.com.cn/problem/P1540

创建一个队列,模拟整个流程。
同时创建一个
bool类型的数组,快速判断元素是否在队列中。
cpp
//
// main.cpp
// 123
//
// Created by Fanz on 2026/3/16.
//
#include <iostream>
#include<queue>
using namespace std;
const int n =1100;
bool mq[n]={false};
int main()
{
queue<int> q;
int M,N,cnt=0;//cnt用来记录查询了多少次字典
cin>>M>>N;
while(N--)
{
int x;
cin>>x;
if(!mq[x])//如果不在内存中
{
if(q.size()<M)
{
mq[x]=true;
q.push(x);
cnt++;
}
else
{
mq[q.front()]=false;
mq[x]=true;
q.pop();
q.push(x);
cnt++;
}
}
}
cout<<cnt;
}
3. 海港(这道题不错!)
https://www.luogu.com.cn/problem/P2058
【解法】先来的乘客,在时间逐渐增大的时候会先出列。因此,可以用队列模拟整个过程。
- 队列里面存每一个乘客,需要存储乘客的编号还有进队的时间;
- 进队的时候,把队列里面时间差大于等于 24 小时的全出队,然后统计队列里面国家的个数;
- 需要额外创建一个
mp数组来统计队列里面各个国家的人数,方便在进出队的时候,统计国家的个数。
cpp
#include<bits/stdc++.h>
using namespace std;
const int N =1e5+10;
typedef pair<int,int> PII;//第一int是时间,第二个int是国籍
int mp[N];//记录第i号国家的人数
int cnt;//记录总共多少国家
int main()
{
queue<PII> q;
int n;
cin>>n;
while(n--)
{
int t,num;
cin>>t>>num;
while(num--)
{
int x;
cin>>x;
q.push({t,x});
if(mp[x]++==0)//判断是不是第一个这个国籍的人
{
cnt++;
}
}
//判断队列合法性 即是否有人因为超过24h要离开队列 并关注国家数量的情况
while(q.size()&&t-q.front().first>=86400)
//这道题主播测试过 不管有没有加 q.size()这个条件都能AC 就是说不会有空船的现象
//但是这个题目描绘的很糙🥚!害主播还考虑空船该咋办 可恶!
{
int con=q.front().second;
if(--mp[con]==0) cnt--;
q.pop();
}
cout<<cnt<<endl;
}
return 0;
}
