A
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
string l;
int main()
{
int t;cin>>t;
while(t--)
{
stack <int> a;
queue <int> b;
int k,flaga=0,flagb=0; cin>>k;
for(int i=0;i<k;i++)
{
cin>>l;
if(l=="push")
{
int x;cin>>x;
a.push(x);
b.push(x);
}
else
{
if(a.size()==0)
flaga=1;
else
a.pop();
if(b.size()==0)
flagb=1;
else
b.pop();
}
}
if(flagb==1) printf("error");
else
{
while(!b.empty())
{
printf("%d ",b.front());
b.pop();
}
}
printf("\n");
if(flaga==1) printf("error");
else
{
int y=a.size(),p[y],i=0;
while(!a.empty())
{
int u=a.top();
p[i]=u;
a.pop();i++;
}
for(int i=y-1;i>=0;i--)
printf("%d ",p[i]);
}
printf("\n");
}
return 0;
}
1. stack 从后往前进行删除操作;
2. queue 从前往后进行删除操作;
3. stack 输出时要注意为逆向输出;(可以把 stack理解为“积木”的堆积方式(输入时是从下往上堆积,需要输出是则从上往下拿取));
B
#include<iostream>
using namespace std;
int main()
{
string s;
while(cin>>s)
{
int a[110]={0},b[110]={0},t=0;
for(int i=0;i<s.size();i++)
{
if(s[i]=='(')
{
a[++t]=i;
b[i]=1;
}
if(s[i]==')')
{
b[i]=2;
if(t>0)
{
b[a[t]]=0;
b[i]=0;
t--;
}
}
}
cout<<s<<endl;
for(int i=0;i<s.size();i++)
{
if(b[i]==1) printf("$");
else if(b[i]==2) printf("?");
else printf(" ");
}
cout<<endl;
}
return 0;
}
**数据较小,用的数组;
1. 注意每次数组应该初始化一下**;
C
#include<iostream>
#include<queue>
using namespace std;
queue <int> a,b;
void ssy(int k)
{
int i=1;
while(!a.empty())
{
if(i%k!=0)
b.push(a.front());
a.pop();
i++;
}
}
void sy(int k)
{
int i=1;
while(!b.empty())
{
if(i%k!=0)
a.push(b.front());
b.pop();
i++;
}
}
int main()
{
int n; cin>>n;
while(n--)
{
int x; cin>>x;
for(int i=1;i<=x;i++)
a.push(i);
int i=0;
while(a.size()>3||b.size()>3)
{
if(i%2)
ssy(2);
else
sy(3);
i++;
}
int g=0;
while(!a.empty())//最后结束时在队列 a 中
{
if(g==0)
{
printf("%d",a.front()); g=1;
}
else
printf(" %d",a.front());
a.pop();
}
g=0;
while(!b.empty())//最后结束时在队列 b 中
{
if(g==0)
{
printf("%d",b.front()); g=1;
}
else
printf(" %d",b.front());
b.pop();
}
cout<<endl;
}
return 0;
}