栈是一种先进后出、只允许在一端进行插入或删除的线性的数据结构。
主要就是对栈的基本操作。
int st[N];//设置一个栈
int top=-1;//刚开始的栈顶为空
部分代码:
string op;
cin>>op;
if(op=="push")//对栈的插入
{
int x;
cin>>x;
st[++top]=x;
}
else if (op=="pop")//对栈的删除
{
top--;
}
else if(op=="query")//返回栈顶元素
{
cout<<st[top]<<endl;
}
else if(op=="empty")//判断栈是否为空
{
if(top==-1)
{
cout<<"YES"<<endl;
}
else
cout<<"NO"<<endl;
}
这一题的思路基于树的操作,外部节点是数,内部节点是运算符,在判断优先级的基础上对表达式进行计算。
代码如下:
#include <iostream>
#include <cstring>
#include <stack>
#include <unordered_map>
using namespace std;
stack<int> num;
stack<char> op;
unordered_map<char,int> pr={{'+',1},{'-',1},{'*',2},{'/',2}};
//unordered_map是一个关联容器,它将键值对存储在哈希表中,
//可以快速地查找和访问元素。它的键和值可以是任何类型,但是键必须是唯一的。
//与map相比,unordered_map的插入、删除和查找操作都更快,但是它的元素是无序的。
void eval()
{
int b=num.top();//先入栈后计算
num.pop();
int a=num.top();
num.pop();
char c=op.top();
op.pop();
int x;
if(c=='+')
x=a+b;
else if(c=='-')
x=a-b;
else if(c=='*')
x=a*b;
else
x=a/b;
num.push(x);
}
int main()
{
string s;
cin>>s;
for(int i=0;i<s.size();i++)
{
char c=s[i];
if(isdigit(c))//如果是数字的话,提取压入栈
{
int x=0,j=i;
while(j<s.size()&&isdigit(s[j]))
x=x*10+s[j++]-'0';
i=j-1;
num.push(x);
}
else if(c=='(') op.push(c);//如果是(,就压入栈,开始进行优先级高的运算
else if(c==')')//逆序计算
{
while(op.size()&&op.top()!='(')
eval();
op.pop();
}
else //普通运算符就比较优先级
{
while(op.size()&&pr[op.top()]>=pr[c])
eval();
op.push(c);
}
}
while(op.size())//如果运算符栈不为空的话,就继续进行运算
eval();
cout<<num.top()<<endl;
return 0;
}
这个问题需要在保证输出的字典序是从小到大的基础上实现,可以在实现的过程中就将输出的结果排好序,建立并维护三个栈是比较简便的方法。
代码如下:
#include <iostream>
#include <vector>
#include <stack>
//建立三个状态,分别是已出栈,在栈中,和未进栈
using namespace std;
//如何使state1的字典序维持在从小到大的状态?
//先将state2的出栈,再将state3进栈
//这样得到的是一个更小的字典序
//state1(<n时)的数一定小于state2的,state2的一定小于state3的数,
//state3这个更大的数进栈之后,只有先出栈排到state1之后,state2中比state3小的数
//才能出栈,这样得到的不会是更小的字典序
int n,cnt=20;//按字典序输出前20种情况
vector<int> state1;//维护出栈的序列
stack<int> state2;
int state3=1;
void dfs() //数据范围小,直接用暴力搜索
{
if(!cnt)//如果到了前20次就返回
return ;
if(state1.size()==n)//如果状态1全部出栈
{
cnt--;
for(auto x : state1)//将元素全部输出
cout<<x;
cout<<endl;
return ;
}
if(state2.size()) //如果状态2不为0,说明要继续进行出栈操作
{
state1.push_back(state2.top());
state2.pop();
dfs();
state2.push(state1.back());
state1.pop_back();
}
if(state3<=n) //如果状态3还在范围内,继续进行进栈操作
{
state2.push(state3);
state3++;
dfs();
state3--;
state2.pop();
}
}
int main()
{
scanf("%d",&n);
dfs();
return 0;
}
单调栈分为单调递增栈和单调递减栈,在解决需要比较前后元素的大小关系时常用到。
核心代码:
while (n -- )
{
int x;
cin>>x;
while(top && st[top]>=x)//如果栈不为空并且当前栈的元素大于x,
//栈中元素出栈,直到比x小
top--;
if(!top)//如果栈为空。那么就没有x小的数,此时输出-1
printf("-1 ");
else //栈不为空,X可以一直入栈,
//那么说明X即将入栈前的栈顶元素就是左边第一个比它小的数
printf("%d ",st[top]);
st[++top]=x;//将x入栈
}