本次训练共6题,本文附AC代码和题目链接。
nefu 1630 栈-括号匹配
#include <bits/stdc++.h>
using namespace std;
string a;
stack<char>s;
int main()
{
cin>>a;
for(int i=0;i<a.length();i++)
{
if(s.empty()||a[i]=='('||a[i]=='['){s.push(a[i]);continue;}
if(s.top()=='('&&a[i]==')')s.pop();
else if(s.top()=='['&&a[i]==']')s.pop();
else s.push(a[i]);
}
if(s.empty())printf("OK\n");
else printf("Wrong\n");
return 0;
}
nefu 1624 栈-程序员输入问题
把字符串从前往后遍历,是#就出栈,是@就清栈,其他的直接入栈
然后把这个栈弄到另外一个栈里,再依次输出另外一个栈的栈顶即可
#include <bits/stdc++.h>
using namespace std;
string a;
stack<char>s1,s2;
int main()
{
ios::sync_with_stdio(false);
getline(cin,a);//输入带空格的字符串
for(int i=0;i<a.length();i++)
{
if(a[i]=='@'){while(!s1.empty())s1.pop();}
else if(a[i]=='#')s1.pop();
else s1.push(a[i]);
}
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
while(!s2.empty())
{
printf("%c",s2.top());
s2.pop();
}
printf("\n");
return 0;
}
nefu 1629 栈-洗盘子
#include <bits/stdc++.h>
using namespace std;
stack<int>s1,s2,s3;
int main()
{
int n,x,flag;
cin>>n;
for(int i=n;i>=1;i--)//注意初始入栈是n到1不是1到n
s1.push(i);
while(!(s1.empty()&&s2.empty()))
{
cin>>flag>>x;
if(flag==1)
{
while(x--&&!s1.empty())
{s2.push(s1.top());s1.pop();}
}
if(flag==2)
{
while(x--&&!s2.empty())
{s3.push(s2.top());s2.pop();}
}
}
while(!s3.empty())
{printf("%d\n",s3.top());s3.pop();}
return 0;
}
nefu 1627 栈-溶液模拟器
#include <bits/stdc++.h>
using namespace std;
typedef struct
{
int v;
double c;
}liquid;
stack<liquid>vis;
int main()
{
int n,v0,v1,v2,v3;
double c0,c1,c2,c3;
string str;
ios::sync_with_stdio(false);
cin>>v0>>c0>>n;
vis.push({v0,c0});
while(n--)
{
cin>>str;
if(str=="P")
{
liquid tmp=vis.top();
v1=tmp.v;c1=tmp.c;
cin>>v2>>c2;
v3=v1+v2;
c3=(v1*c1+v2*c2)/v3;
printf("%d %.5lf\n",v3,c3);
vis.push({v3,c3});
}
if(str=="Z")
{
if(vis.size()==1)
printf("%d %.5lf\n",v0,c0);
if(vis.size()>1)
{
vis.pop();
liquid tmp=vis.top();
printf("%d %.5lf\n",tmp.v,tmp.c);
}
}
}
return 0;
}
nefu 1628 栈-火车编组
#include <bits/stdc++.h>
using namespace std;
int n,p,a[110];
stack<int>s;
int main()
{
ios::sync_with_stdio(false);
cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i];//出栈的编号
p=1;
for(int i=1;i<=n;i++)
{
if(i<=a[p]){s.push(i);printf("A");}
if(i==a[p])
{
while(!s.empty()&&s.top()==a[p])
{
s.pop();
printf("B");
p++;
}
if(p==n+1)break;
}
}
printf("\n");
return 0;
}
nefu 1631 栈-表达式求值
这题不用栈也可以做。
#include <bits/stdc++.h>
using namespace std;
const int mod=1e4;
char c;
int x,sum,ans;
int main()
{
scanf("%d",&x);sum=x%mod;//sum为连乘式的值
while(scanf("%c",&c)&&c!='\n')
{
scanf("%d",&x);
x=x%mod;
if(c=='*')sum=sum*x%mod;
else {ans=ans+sum%mod;sum=x%mod;}
}
ans=ans+sum%mod;//处理最后可能剩下的一个单独的数字
printf("%d\n",sum%mod);
return 0;
}
今天这六道题就到此为止了,栈确实还挺好用的。