C++ STL之queue详解

返回主目录

3 queue

3.1 介绍

队列是一种先进先出的数据结构。

//头文件
#include<queue>
//定义初始化
queue<int> q;

3.2 方法函数

代码含义
q.front()返回队首元素 O ( 1 ) O(1) O(1)
q.back()返回队尾元素 O ( 1 ) O(1) O(1)
q.push(element)尾部添加一个元素element 进队 O ( 1 ) O(1) O(1)
q.pop()删除第一个元素 出队 O ( 1 ) O(1) O(1)
q.size()返回队列中元素个数,返回值类型unsigned int O ( 1 ) O(1) O(1)
q.empty()判断是否为空,队列为空,返回true O ( 1 ) O(1) O(1)

3.3 队列模拟

使用q[]数组模拟队列

hh表示队首元素的下标,初始值为0

tt表示队尾元素的下标,初始值为-1,表示刚开始队列为空

一般来说单调栈和单调队列写法均可使用额外变量 tthh 来进行模拟
如有学习余力可学习 单调队列详解

#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
int q[N];

int main() {
	int hh = 0,tt = -1;
//	入队 
	q[++tt] = 1;
	q[++tt] = 2; 
//	将所有元素出队 
	while(hh <= tt) {
		int t = q[hh++];
		printf("%d ",t);
	}
	return 0;
 } 

3.4 队列模拟例题

题目链接: https://atcoder.jp/contests/abc247/tasks/abc247_d

#include<bits/stdc++.h>
using namespace std;

using ll = long long ;
using pii = pair<int, int>;
const int N = 250005, mod = 998244353;

int q[N], num[N];

void solve() {
	int qq, hh = 0, tt = -1;
	cin >> qq;
	while(qq--) {
		int op;
		cin >> op;
		int x, c;
		if(op == 1) {
			cin >> x >> c;
			q[++tt] = c;
			num[tt] = x;
		} else {
			cin >> c;
			ll res = 0;
			while(c) {
				if(q[hh] > c) {
					q[hh] -= c;
					res += 1ll * c * num[hh];
					break;
				} else {
					res += 1ll * q[hh] * num[hh];
					c -= q[hh++];
				}
			}
			cout << res << "\n";
		}
	}
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);

	int t;
	// cin >> t;
	t = 1;
	while(t--)
		solve();
	return 0;
}

如要获取所有内容的PDF文件,请在公众号【行码棋】回复【STL】获取,非常抱歉了。
Update:2023-12-11更新PDF文件

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

行码棋

码字好辛苦,总结好吃力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值