正文
一、 队列概述
1. 队列
直接看图
2. 循环队列
逻辑同上,不过会为一个循环的状态运转队首的上一个是队尾,如图
二、 洛谷P1540
1. STL queue
上代码
#include <bits/stdc++.h>
using namespace std;
#define ONLINE_JUDGE
bool Hash[1005];
queue<int> mem;
int m, n;
inline void problem() {
scanf("%d%d", &m, &n);
int cnt = 0;
int a;
while (n -- ) { // 循环输入查询的字
scanf("%d", &a);
if (!Hash[a]) { // 在哈希里找有没有这个字
++cnt; // 没有找到就记一次数
mem.push(a); // 然后push进队列
Hash[a] = 1; // 记为存储在队列中
while (mem.size() > m) { // 循环pop掉超出队列内存的内容
Hash[mem.front()] = 0;
mem.pop();
}
}
}
printf("%d\n", cnt);
}
int main() {
// ios::sync_with_stdio(0);
// cin.tie(0), cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
problem();
return 0;
}
2. 手写循环队列
上代码
#include <bits/stdc++.h>
using namespace std;
#define ONLINE_JUDGE
const int N = 1003;
int m, n;
int Hash[N];
struct myqueue {
int data[N];
int head, rear;
bool init() {
head = rear = 0;
return true;
}
int size() {
return (rear - head + N) % N;
}
bool empty() {
if (size() == 0) {
return true;
} else {
return false;
}
return true;
}
bool push(int e) {
if ((rear + 1) %N == head) {
return false;
}
data[rear] = e;
rear = (rear + 1) % N;
return true;
}
bool pop(int &e) {
if (head == rear) {
return false;
}
e = data[head];
head = (head + 1) % N;
return true;
}
int front() {
return data[head];
}
};
myqueue Q;
inline void problem() {
Q.init();
int m, n;
scanf("%d%d", &m, &n);
int cnt = 0;
while (n--) {
int en;
scanf("%d", &en);
if (!Hash[en]) {
++cnt;
Q.push(en);
Hash[en] = 1;
while (Q.size() > m) {
int tmp; // 用于存储删了什么
Q.pop(tmp);
Hash[tmp] = 0;
}
}
}
printf("%d\n", cnt);
}
int main() {
// ios::sync_with_stdio(0);
// cin.tie(0), cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
problem();
return 0;
}