c++ 刷题:-【C/C++刷题集】栈、stack、队列、queue核心精讲 - j++) {

📅 2026-11-30 👤 拼多多助力营销技巧 📂 拼多多助力平台 👁️ 222 次阅读

﫧个人主页:小年糕是糕手

个人专栏:《C++》《Linux》《数据结构》《Blender 修行笔记》

你不能左右天气,但你可以改变心情;你不能改变过去,但你可以决定未来!

目录

一、栈和stack

【模板】栈

有效的括号

验证栈序列

后缀表达式

括号序列

二、队列和queue

【模板】队列

机器翻译

海港

一、栈和stack

【模板】栈

【模板】栈

其实这道题非常简单,唯一需要注意的点就是:

如果我们直接使用int类型变量就会造成下面的情况:

#include

#include

using namespace std;

const int N = 1e6 + 10;

unsigned long long stk[N]; // 存储元素,支持 64 位无符号整数

int n; // 栈中元素个数

void push(unsigned long long x) {

stk[n++] = x;

}

bool empty() {

return n == 0;

}

void pop() {

if (!empty())

n--;

else

cout << "Empty\n";

}

void query() {

if (!empty())

cout << stk[n - 1] << '\n';

else

cout << "Anguei!\n";

}

void get_size() {

cout << n << '\n';

}

int main() {

ios::sync_with_stdio(false);

cin.tie(nullptr);

int T;

cin >> T;

while (T--) {

n = 0; // 每组数据重置栈

int op_cnt;

cin >> op_cnt;

string op;

for (int i = 0; i < op_cnt; ++i) {

cin >> op;

if (op == "push") {

unsigned long long x;

cin >> x;

push(x);

}

else if (op == "pop") {

pop();

}

else if (op == "query") {

query();

}

else if (op == "size") {

get_size();

}

}

}

return 0;

}

有效的括号

有效的括号

bool isValid(string s) {

stackst; // 创建一个字符栈

for (auto ch : s) { // 遍历字符串中的每个字符 ch

if (ch == '(' || ch == '{' || ch == '[') // 如果是左括号

st.push(ch); // 压入栈

else { // 否则就是右括号

if (st.empty()) // 栈空说明没有对应的左括号

return false;

char left = st.top(); // 获取栈顶的左括号

// 判断左右是否匹配

if (ch == ')' && left != '(') return false;

if (ch == ']' && left != '[') return false;

if (ch == '}' && left != '{') return false;

st.pop(); // 匹配成功,弹出栈顶

}

}

return st.empty(); // 全部处理完后,栈空才说明完全匹配

}

核心思想:栈(后进先出)

遍历字符串的每一个字符:

如果是左括号((、{、[),就把它压入栈中。 如果是右括号()、}、]),就检查栈顶的左括号是否与它匹配:

如果栈为空,说明没有左括号可匹配 → 无效。 如果栈顶的左括号与当前右括号不配对(例如 ) 对 {)→ 无效。 如果匹配,就把栈顶的左括号弹出,继续处理下一个字符。

最后,如果栈中还有剩余左括号(比如 "((()"),也说明不匹配,所以返回 st.empty()。

举例理解

以 s = "([{}])" 为例:

'(' 左括号 → 压入栈 [ ( ] '[' 左括号 → 压入栈 [ ( , [ ] '{' 左括号 → 压入栈 [ ( , [ , { ] '}' 右括号 → 栈顶是 {,匹配 → 弹出 { → 栈 [ ( , [ ] ']' 右括号 → 栈顶是 [,匹配 → 弹出 [ → 栈 [ ( ] ')' 右括号 → 栈顶是 (,匹配 → 弹出 ( → 栈空 最后栈空 → 返回 true,有效。

验证栈序列

验证栈序列

#include

#include

using namespace std;

const int N = 1e5 + 10;

int n;//序列长度

int a[N], b[N];

int main()

{

int q;//q次询问次数

cin >> q;

while (q--)

{

cin >> n;

for (int i = 1; i <= n; i++)

cin >> a[i];

for (int i = 1; i <= n; i++)

cin >> b[i];

stackst;

int j = 1;

for (int i = 1; i <= n; i++)

{

//让元素依次进栈

st.push(a[i]);

while (j <= n && st.size() && st.top() == b[j])

{

//出栈

st.pop();

j++;

}

}

if (st.size()) cout << "No" << endl;

else cout << "Yes" << endl;

}

return 0;

}

这段代码就是模拟一个栈,判断给定的出栈顺序是否可能实现。

过程:依次把入栈序列的数压进栈,每压一个数后,如果栈顶的数正好是下一个要出栈 的数,就把它弹出来,然后继续检查新的栈顶(可能连续弹出多个)。 结果:如果最后所有数都能弹出来(栈为空),输出 Yes,否则 No

后缀表达式

后缀表达式

#include

#include

#include

using namespace std;

int main() {

string s;

cin >> s;

stackst;

int i = 0;

while (s[i] != '@')

{

if (isdigit(s[i]))

{

int num = 0;

while (isdigit(s[i]))

{

num = num * 10 + (s[i] - '0');

i++;

}

// 此时 s[i] 应该是 '.'

st.push(num);

i++; // 跳过 '.'

}

else

{

// 运算符

int b = st.top(); st.pop(); // 右操作数

int a = st.top(); st.pop(); // 左操作数

switch (s[i]) {

case '+': st.push(a + b); break;

case '-': st.push(a - b); break;

case '*': st.push(a * b); break;

case '/': st.push(a / b); break;

}

i++;

}

}

cout << st.top() << endl;

return 0;

}

括号序列

括号序列

这题其实和上述的有效的括号是非常类似的,我们的思路应该是先去做一下括号匹配,在匹配的过程中同时标记一下哪些括号没有匹配成功,给没有匹配成功的括号配对一下即可:

#include

#include

#include

using namespace std;

const int N = 1e2 + 10;

bool st[N];//标记是否已经匹配

int main()

{

string s; cin >> s;

int n = s.size();

stackstk; // ⾥⾯存的是左括号的下标

string ret;

for (int i = 0; i < n; i++)

{

if (s[i] == '(' || s[i] == '[')

{

stk.push(i);

}

else

{

if (stk.empty()) continue;

char ch = s[stk.top()];

if ((ch == '(' && s[i] == ')') || (ch == '[' && s[i] == ']')) // 能匹配

{

st[stk.top()] = true;

st[i] = true;

stk.pop();

}

}

}

for (int i = 0; i < n; i++)

{

char ch = s[i];

if (st[i]) ret += ch;

else

{

// 不能匹配就要加括号

if (ch == '(')

{

ret += ch;

ret += ')';

}

else if (ch == ')')

{

ret += '(';

ret += ch;

}

else if (ch == '[')

{

ret += ch;

ret += ']';

}

else if (ch == ']')

{

ret += '[';

ret += ch;

}

}

}

cout << ret << endl;

return 0;

}

二、队列和queue

【模板】队列

【模板】队列

#include

using namespace std;

const int N = 1e5 + 10;

int que[N];

int h = 0; // 队头指针,指向第一个元素

int t = 0; // 队尾指针,指向即将插入的位置

// 入队

void push(int x) {

que[t] = x; // 先赋值,再把尾指针后移

t++;

}

// 判断队列是否为空

bool empty() {

return h == t; // 头指针等于尾指针,队列为空

}

// 出队

void pop() {

if (empty()) {

// 如果为空,输出错误

cout << "ERR_CANNOT_POP" << endl;

}

else {

// 如果不为空,队头指针后移即可

h++;

}

}

// 查询队首

void query() {

if (empty()) {

// 如果为空,输出错误

cout << "ERR_CANNOT_QUERY" << endl;

}

else {

// 如果不为空,输出队首

cout << que[h] << endl;

// 注意:query 不能移动指针 h!

}

}

// 返回队列大小

int size_() { // 改名 size 为 size_ 避免冲突

return t - h; // 尾指针 - 头指针 = 元素个数

}

int main() {

int n;

cin >> n;

while (n--) {

int op;

cin >> op;

switch (op) {

case 1: { // 1 x : 入队

int x;

cin >> x;

push(x);

break;

}

case 2: // 2 : 出队

pop();

break;

case 3: // 3 : 查询队首

query();

break;

case 4: // 4 : 输出大小

cout << size_() << endl;

break;

}

}

return 0;

}

机器翻译

机器翻译

#include

#include

using namespace std;

int main() {

int M, N;

cin >> M >> N;

queuememory; // 内存队列(存储单词)

bool inMemory[1010] = {false}; // 标记单词是否在内存中(单词 ≤ 1000)

int cnt = 0; // 查词典次数

for (int i = 0; i < N; i++) {

int word;

cin >> word;

// 如果单词不在内存中

if (!inMemory[word]) {

cnt++; // 需要查词典

// 如果内存满了

if (memory.size() == M) {

int outWord = memory.front(); // 最早进入内存的单词

memory.pop();

inMemory[outWord] = false; // 标记为不在内存

}

// 放入新单词

memory.push(word);

inMemory[word] = true;

}

// 如果单词已在内存中,什么都不做 拼多多帮助力入口

}

cout << cnt << endl;

return 0;

}

代码说明:

queuememory:模拟内存的队列(先进先出) bool inMemory[1010]:快速判断单词是否在内存中(单词大小 ≤ 1000) 遇到新单词时:计数 +1,若内存满则弹出队首,再入队新单词 遇到已在内存的单词:直接跳过,不操作队列

时间复杂度: O(N) 空间复杂度: O(M + 单词范围)

海港

海港

滑动窗口时间范围 时间窗口是 86400 秒,即 t_i - 86400 < t_p ≤ t_i。 我们只需要维护一个队列,里面存放“当前还在 24 小时内到达的船上的所有乘客的国籍”。 队列存储结构 队列中的每个元素是一个乘客的 (国籍, 到达时间),或者直接按船只顺序处理。 更高效的方法是:

用一个队列 q 存储 (船到达时间, 乘客国籍列表) 用 total[100001] 统计每个国籍在当前窗口内的出现次数 用 diff_count 记录当前窗口内不同国籍的数量 处理过程

每次来一艘新船,先把它的所有乘客加入窗口(增加国籍计数,若从 0→1 则 diff_count++) 把船整体推入队列(记录到达时间) 检查队列头部的船:如果 当前时间 - 船到达时间 ≥ 86400,则把该船的所有乘客从窗口中移除(减少国籍计数,若从 1→0 则 diff_count--) 输出当前的 diff_count

时间复杂度

每个乘客入队一次、出队一次 → O(∑k_i) 国籍计数数组访问 O(1) 总复杂度 O(n + ∑k_i),满足 1e5 船只、3e5 乘客的数据规模

#include

#include

using namespace std;

const int MAX_NATION = 100001;

struct Ship {

int t; // 到达时间

int k; // 乘客数量

int* nations; // 乘客国籍数组(动态分配)

};

int main() {

ios::sync_with_stdio(false);

cin.tie(nullptr);

int n;

cin >> n;

queueq; // 存储船只(按到达顺序)

int nationCount[MAX_NATION] = {0}; // 每种国籍在当前窗口内的出现次数

int diffNations = 0; // 当前窗口内不同国籍的数量

for (int i = 0; i < n; i++) {

int t, k;

cin >> t >> k;

int* nations = new int[k];

for (int j = 0; j < k; j++) {

cin >> nations[j];

// 增加国籍计数

if (nationCount[nations[j]] == 0) {

diffNations++;

}

nationCount[nations[j]]++;

}

// 当前船入队

q.push({t, k, nations});

// 移除超出 24 小时的船只

while (!q.empty() && t - q.front().t >= 86400) {

Ship old = q.front();

q.pop();

for (int j = 0; j < old.k; j++) {

int nat = old.nations[j];

nationCount[nat]--;

if (nationCount[nat] == 0) {

diffNations--;

}

}

delete[] old.nations; // 释放内存

}

// 输出当前窗口的不同国籍数量

cout << diffNations << '\n';

}

return 0;

}

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧