【2022.11.14】2. 队列(1) --- 洛谷P1540

正文

一、 队列概述

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;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值