跳到正文

题解

10.基础栈、队列

dhx0204约 24 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 24 分钟

版本

  1. v1当前

一、栈 1、手写栈

2、stack的使用

例题1:P1739 表达式括号匹配

题目:一个程序检查表达式中的左右圆括号是否匹配,若匹配,则返回“YES”;否则返回“NO”。表达式长度小于255,左圆括号少于20个。

解析:遇到(入栈,遇到),取栈顶元素匹配,若匹配则出栈,否则程序结束。

C++
#include <bits/stdc++.h>
using namespace std;
stack<char> q;
char k;
int main() {
    while (1) {
        cin >> k;
        if (k == '@')
            break;
        if (k == '(') {
            q.push(k);
        }
        if (k == ')') {
            if (q.empty()) {
                cout << "NO";
                return 0;
            }
            if (q.top() == '(')
                q.pop();
            else {
                cout << "NO";
                return 0;
            }
        }
    }
    if (q.empty())
        cout << "YES";
    else
        cout << "NO";
    return 0;
}

例题2:P1449 后缀表达式

后缀表达式:遇到运算数入栈,遇到运算符就取栈顶2个运算数进行运算,并将答案入栈。注意运算数的处理。

C++
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int main() {
    stack<int> q;
    string s;
    getline(cin, s);
    int t = 0;
    for (int i = 0; i < s.size(); i++) {
        char c = s[i];
        if (c == '@')
            break;
        if (isdigit(c)) {//检查参数c是否为十进制数字字符。
            t = t * 10 + (c - '0');
            if (!isdigit(s[i + 1])) {//如果下一个不是数字字符,即空格,则直接把数字push入栈
                q.push(t);
                t = 0;
            }
        } else if (c == '+' || c == '-' || c == '*' || c == '/') {
            int x = q.top(), ans = 0;
            q.pop();
            int y = q.top();
            q.pop();
            if (c == '+')
                ans = y + x;
            else if (c == '-')
                ans = y - x;
            else if (c == '*')
                ans = y * x;
            else if (c == '/')
                ans = y / x;
            q.push(ans);
        }
    }
    printf("%d", q.top());
    return 0;
}

例题3:P1981 [NOIP 2013 普及组] 表达式求值

仅有数字和+*。可以先计算乘法,再处理加法

C++
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MAXN = 1e5 + 10;
string s;
ll x, ans = 0;
char op;
stack<ll> nums;
int main() {
    scanf("%lld", &x);
    nums.push(x);
    while (cin >> op >> x) {
        if (op == '+')
            nums.push(x);
        else {
            int t = (nums.top() * x) % 10000;
            nums.pop();
            nums.push(t);
        }
    }
    while (nums.size()) {
        ans = (ans + nums.top()) % 10000;
        nums.pop();
    }
    printf("%lld", ans);
    return 0;
}

例题4:P4387 【深基15.习9】验证栈序列(C. 出栈顺序)

C++
#include <bits/stdc++.h>
using namespace std;
stack<int> st;
int a[100010], r[100010];
void work() {
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++) cin >> r[i];
    for (int i = 1; i <= n; i++) cin >> a[i];
    int sum = 1;
    for (int i = 1; i <= n; i++) {
        st.push(r[i]);
        while (st.top() == a[sum]) {
            st.pop();
            sum++;
            if (st.empty())//注意栈为空时,不再继续!!!
                break;
        }
    }
    if (st.empty())
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
    while (!st.empty()) st.pop();//每次执行完,需要清空栈!!!
}
int main() {
    int t;
    cin >> t;
    while (t--) {
        work();
    }
    return 0;
}

例题5:P1165 日志分析(D)

C++
#include <bits/stdc++.h>
using namespace std;
int n, k, x;
stack<int> q;
int main() {
    cin >> n;
    while (n--) {
        cin >> k;
        if (k == 0) {//插入
            cin >> x;
            if (q.empty())
                q.push(x);
            else
                q.push(max(q.top(), x));
        } else if (k == 1) {//删除 栈顶元素 :不需要明确栈顶元素是什么
            if (!q.empty())
                q.pop();
        } else if (k == 2) {//查询栈顶元素 :使用栈顶元素记录栈中最大值
            if (!q.empty())
                cout << q.top() << endl;
            else
                cout << 0 << endl;
        }
    }
    return 0;
}

手写栈

C++
#include <bits/stdc++.h>
using namespace std;
int f[200001], n, x, y, t = 0;
int main() {
    cin >> n;
    f[0] = 0;
    for (int i = 1; i <= n; i++) {
        cin >> x;
        if (x == 0) {
            cin >> y;
            t++;
            f[t] = max(f[t - 1], y);
        }
        if (x == 1)
            if (t != 0)
                t--;
        if (x == 2)
            cout << f[t] << endl;
    }
    return 0;
}

例题6:程序员 注意手写栈和stack的区别

C++
#include <bits/stdc++.h>
using namespace std;
stack<char> a;
int main() {
    string s;
    getline(cin, s);
    //遇到的既不是#也不是@,把字符存入栈
    //遇到#就把栈顶弹出
    //遇到@,清栈
    for (int i = 0; i < s.size(); i++) {
        if (s[i] != '#' && s[i] != '@') {
            a.push(s[i]);
        } else if (s[i] == '#') {
            if (!a.empty()) {
                a.pop();
            }
        } else if (s[i] == '@') {
            while (!a.empty()) {
                a.pop();
            }
        }
    }
    s.clear();  //清空字符串
    while (!a.empty()) {
        s += a.top();
        a.pop();
    }
    reverse(s.begin(), s.end());
    cout << s;
    return 0;
}
C++
#include <bits/stdc++.h>
using namespace std;
string s;
char c[105];
int tot;
int main() {
    getline(cin, s);
    for (int i = 0; i < s.size(); i++) {
        if (s[i] != '#' && s[i] != '@')
            c[++tot] = s[i];
        else {
            if (s[i] == '@')
                tot = 0;
            else
                tot--;
        }
    }
    for (int i = 1; i <= tot; i++) {
        cout << c[i];
    }
    return 0;
}

例题7:中缀表达式值(expr)

C++
#include<bits/stdc++.h>
using namespace std;
//整体思路:中缀表达式先转为后缀表达式,再计算;
//1、先检查表达式是否合法 :*/^两边是否有数字;括号是否匹配
string s;
int sum[1000100];
stack<int>num; //存放运算数
stack<char>ch; //存放运算符
int level(char c){
	if(c=='+'||c=='-') return 1;
	else if(c=='*'||c=='/')return 2;
	return 0;
}
void ys(){
	int x=num.top();
	num.pop();
	int y=num.top();
	num.pop();
	char c=ch.top();
	ch.pop();
	if(c=='+')      num.push(y+x);
	else if(c=='-') num.push(y-x);
	else if(c=='*') num.push(y*x);
	else if(c=='/') num.push(y/x);
}
int main(){
	getline(cin,s);//输入中缀表达式,@结束
	int len =s.length()-1;
	//1、判断表达式是否合法
	if(s[0]=='-') num.push(0) ;//1.1判断第一个字符是否为-
	if(s[0]=='+'||s[0]=='*'||s[0]=='/') {
		cout<<"NO"<<endl;
		return 0;
	}

	for(int i=1;i<len;i++){
		if(level(s[i]) && level(s[i-1])){//1.2运算符不能相邻
			cout<<"NO"<<endl;
			return 0;
		}
	}

	int sum=0;
	for(int i=0;i<len;i++){//1.3判断()是否匹配
		if(s[i]=='(') sum++;
		else if(s[i]==')') sum--;
	}
	if(sum!=0){
		cout<<"NO"<<endl;
		return 0;
	}
	//2.进行中缀转后缀 ,边转边计算
	int x=0;   //构造运算数
	bool f=0;  //标记是否已完成一个运算数的构造
	for(int i=0;i<len;i++){
		if(isdigit(s[i])){//2.1遍历字符串表达式,构造运算数
			x=x*10+s[i]-'0';
			f=1;
		}else{//如果不再是数字,则将已构造好的运算数入栈
			if(f){
				num.push(x);
				x=0;
				f=0;
			}
			if(s[i]=='(') {     //2.2如果是(则入栈
				ch.push(s[i]);
			}else if(s[i]==')'){//2.3如果是)则
				while(ch.top()!='('){//将ch运算符栈中栈顶元素取出,并进行运算
					ys();
				}
				ch.pop(); //将(出栈
			}else{        //2.4 如果栈不为空,则把当前运算符s[i]和ch栈顶运算符进行比较,若栈顶优先级 较高,则优先使用栈顶运算符进行计算
				while(!ch.empty() && level(ch.top())>=level(s[i])) {
					ys();
				}
				ch.push(s[i]);//将当前运算符s[i]加入栈ch
			}
		}
	}
	if(f) num.push(x);//最后的数字,即入栈
	while(!ch.empty()) ys();//运算符栈中不为空,继续计算
	cout<<num.top()<<endl;//最后运算数num栈中的数据即为运算结果。
	return 0;
}
//(3+4)*5-6@

例题8:P5788 【模板】单调栈

C++
#include<cstdio>
#include<stack>
using namespace std;
int n,a[3000005],f[3000005];//a是需要判断的数组(即输入的数组),f是存储答案的数组
stack<int>s;//模拟用的栈
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++) scanf("%d",&a[i]);
	for(int i=n;i>=1;i--)
	{
		while(!s.empty()&&a[s.top()]<=a[i]) s.pop();//弹出栈顶比当前数小的
		f[i]=s.empty()?0:s.top();//存储答案,由于没有比她大的要输出0,所以加了个三目运算
		s.push(i);//压入当前元素
	}
	for(int i=1;i<=n;i++) printf("%d ",f[i]);//输出
	return 0;
}

例题9:P6510 奶牛排队(绿题 单调栈)

C++
#include <iostream>
#include <cstdio>
#include <stack>
using namespace std;
const int N = 1e5 + 10;
int n, c[N], ans;
int s1[N], t1, s2[N], t2;
int Search() {
    int l = 1, r = t2;
    while (l <= r) {
        int mid = l + r >> 1;
        if (s2[mid] > s1[t1])
            r = mid - 1;
        else
            l = mid + 1;
    }
    return l;
}
int main() {
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
        scanf("%d", &c[i]);
        while (t1 && c[s1[t1]] < c[i]) t1--;
        while (t2 && c[s2[t2]] > c[i]) t2--;
        int pos = Search();
        if (pos != t2 + 1)
            ans = max(ans, i - s2[pos] + 1);
        s1[++t1] = i;
        s2[++t2] = i;
    }
    printf("%d", ans);
    return 0;
}

二、队列

1、队列

例题1:周末舞会(模板题)

C++
#include<bits/stdc++.h>
using namespace std;
queue<int>a,b;
int x,y,z;
int main(){
	cin>>x>>y>>z;
	for(int i=1;i<=x;i++) a.push(i);//队尾插入元素
	for(int j=1;j<=y;j++) b.push(j);
	for(int i=1;i<=z;i++){
		cout<<a.front()<<" "<<b.front()<<endl;     //取队头元素
		a.push(a.front());
		a.pop();  //删除元素
		b.push(b.front());
		b.pop();
	}
	return 0;
}

例题2:P1540 [NOIP 2010 提高组] 机器翻译

C++
#include<iostream>
#include<queue>
using namespace std;
//队列、数组、函数
//模拟法
queue<int>q;//队列q
int m,n,ans;
bool inq[1010];//数组inq
int main(){
	cin>>m>>n;
	for(int i=0;i<n;i++){
		int x;
		cin>>x;
		if(inq[x]) continue;//如果单词已在内存中,直接调用即可,无需查找,查找次数不计数
		else{
			if(q.size()>=m){
				inq[q.front()]=false;
				q.pop();
			}
		q.push(x);
		inq[x]=true;//此处有数字
		ans++; //查字典的次数
		}
	}
	cout<<ans;
	return 0;
}

2、循环队列

例题3:P1996 约瑟夫问题 (循环队列模板题)

问题:n个人,数到m出队,输出出队顺序。

C++
#include<bits/stdc++.h>
using namespace std;
int n,m;
queue<int>q;
int main(){
	cin>>n>>m;
	for(int i=1;i<=n;i++) q.push(i);
	int cnt=1;
	while(!q.empty()){
		if(cnt==m){
			cout<<q.front()<<" ";
			q.pop();
			cnt=1;
		}else{
			q.push(q.front());
			q.pop();
			cnt++;
		}
	}
	return 0;
}

例题4:C. 取牌游戏

k张牌,n个人,m=k/n张good牌,先发给他右手边的人,没发完一轮,需要把接下来的p张依次移到最后,问拿到所有good牌的位置。

C++
#include<bits/stdc++.h>
using namespace std;
int n,k,p;
queue<int>q;
vector<int>a;
int main(){
	cin>>n>>k>>p;//n个人,k张牌,移动p 张纸牌
	for(int i=1;i<=k;i++) q.push(i);
	int x=1;
	while(!q.empty()){
		if(x==n){//2、发完一轮牌之后
			a.push_back(q.front());//保存good牌
			x=0;
		}
		q.pop();//1、发1张牌,就把p张牌移动到队尾
		for(int i=1;i<=p;i++){
			q.push(q.front());
			q.pop();
		}
		x++;//x计数发出去的牌数
	}
	sort(a.begin(),a.end());
	for(int i=0;i<a.size();i++) cout<<a[i]<<endl;
	return 0;
}

例题5:P1563 [NOIP 2016 提高组] 玩具谜题

代码

3、优先队列

例题6:P1090 [NOIP 2004 提高组] 合并果子

C++
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
priority_queue< int, vector<int>, greater<int> >q;
int main(){
	int n;
	cin>>n;
	int x;
	for(int i=0;i<n;i++){
		cin>>x;
		q.push(x);
	}
	long long ans=0;
	while(q.size()>=2){
		int a=q.top();
		q.pop();
		int b=q.top();
		q.pop();
		ans+=a+b;
		q.push(a+b);
	}
	cout<<ans<<endl;
	return 0;
}

4、单调队列

例题7:P1886 滑动窗口 /【模板】单调队列

例题8:P3088 [USACO13NOV] Crowded Cows S(绿题)

C++
#include <bits/stdc++.h>
using namespace std;
struct ppap {
    int x, y;
} a[100001];
ppap qq[100001];
bool q[100001], h[100001];
inline bool cmp(ppap a, ppap b) { return a.x < b.x; }
int main() {
    int n, d;
    scanf("%d%d", &n, &d);//n有牛,d的距离
    for (int i = 1; i <= n; i++) {
        scanf("%d%d", &a[i].x, &a[i].y); //输入坐标和身高
    }
    sort(a + 1, a + n + 1, cmp);//1、按照坐标排序
    int l = 1, r = 0;
    for (int i = 1; i <= n; i++) {
        while (l <= r && qq[r].y < a[i].y) {
            r--;
        }
        qq[++r] = a[i];
        while (l <= r && qq[l].x < a[i].x - d) {
            l++;
        }
        if (qq[l].y >= a[i].y * 2) {
            q[i] = 1;
        }
    }
    memset(qq, 0, sizeof qq);
    l = 1;
    r = 0;
    for (int i = n; i; i--) {
        while (l <= r && qq[r].y < a[i].y) {
            r--;
        }
        qq[++r] = a[i];
        while (l <= r && qq[l].x > a[i].x + d) {
            l++;
        }
        if (qq[l].y >= a[i].y * 2) {
            h[i] = 1;
        }
    }
    int ans = 0;
    for (int i = 1; i <= n; i++) {
        if (q[i] && h[i]) {
            ans++;
        }
    }
    printf("%d", ans);
    return 0;
}

例题8:P2698 [USACO12MAR] Flowerpot S(蓝题)

5、双端队列

移动的琵琶:

例题9:P7935 [COCI 2007/2008 #5] AVOGADRO

例题10:P1160 队列安排( 优先使用双向链表 )

按照一定要求进行排序队列,从左到右输出编号。

代码
原文