线性数据结构-栈
LIFO
薯片的存取
- 括号匹配问题1
给定一个只包含左右括号的合法括号序列,按右括号从左到右的顺序输出每一对配对的括号出现的位置
#include<iostream>
#include<cstdio>
#include<string>
#include<stack>
using namespace std;
int main(){
string s;
cin>>s;
int l=s.length();
stack<int>st;
for(int i=0;i<l;i++){
if(s[i]=='('){
st.push(i);
}
else{
printf("%d %d\n",st.top(),i);
st.pop();
}
}
return 0;
}
- 栈的问题(实际上是找规律)
宁宁考虑的是这样一个问题:一个操作数序列,1,2,…,n
现在可以进行两种操作,
将一个数,从操作数序列的头端移到栈的头端(对应数据结构栈的push操作)
将一个数,从栈的头端移到输出序列的尾端(对应数据结构栈的pop操作)
使用这两种操作,由一个操作数序列就可以得到一系列的输出序列总数
#include<iostream>
#include<cstdio>
int C=0;
using namespace std;
void dfs(stack<int>p,stack<int>st){
if(p.empty()&&st.empty()){
C++;
return 0;
}
if(!p.empty()){
int ing=p.top();
st.push(ing);
p.pop();
dfs(p,st);
p.push(ing);
st.pop();
}
if(!st.empty()){
int ing=st.top();
st.pop();
dfs(p,st);
st.push(ing);
}
}
int main(){
int n;
scanf("%d",&n);
stack<int>a,b;
for(int i=1;i<=n;i++){
a.push(i);
}
dfs(a,b);
printf("%d\n",C);
return 0;
}