问题描述
小Z设计了一种新的数据结构“新壳栈”。首先,它和传统的栈一样支持压入、弹出操作。此外,其栈顶的前c个元素是它的壳,支持翻转操作。其中,c>2是一个固定的正整数,表示壳的厚度。小Z还希望,每次操作,无论是压入、弹出还是翻转,都仅用与c无关的常数时间完成。聪明的你能帮助她编程实现“新壳栈”吗?
程序期望的实现效果如以下两表所示。其中,输入的第一行是正整数c,之后每行输入都是一条指令。另外,如遇弹出操作时栈为空,或翻转操作时栈中元素不足c个,应当输出相应的错误信息。
指令 涵义
1[空格]e 在栈顶压入元素e
2 弹出(并输出)栈顶元素
3 翻转栈顶的前c个元素
0 退出
输入
第一行输入c,之后每行输入都是一条指令,输入以0结束。
输出
对于每个弹出操作,输出栈顶元素,如果栈为空输出“Error: the stack is empty!”。对于每个翻转操作,如果栈中元素不足c个,输出”Error: less than c elements in the stack!“,注意这里的c在输出时以具体输入的c的值代替。
样例输入
3
1 1
1 2
1 3
1 4
3
1 5
3
2
2
2
3
2
2
2
0
样例输出
3
2
5
Error: less than 3 elements in the stack!
4
1
Error: the stack is empty!
算法讨论
挺水的,暴力模拟一下就行了。
#include <cstdio>
using namespace std;
#define maxn 1000000
int a[maxn];
int c,x,l;
int trun()
{
int t=0,p=l;
for (int i=l-c+1;i<=(l-c+1)+c/2;i++)
{
t=a[i];
a[i]=a[p];
a[p]=t;
p--;
}
}
int main()
{
freopen("stk.in","r",stdin);
freopen("stk.out","w",stdout);
scanf("%d",&c);
scanf("%d",&x);
while (x!=0)
{
if (x==1) scanf("%d",&a[++l]);
if (x==2)
if (l==0)
printf("Error: the stack is empty!\n");
else
printf("%d\n",a[l]),l--;
if (x==3)
if (l<c)
printf("Error: less than %d elements in the stack!\n",c);
else
trun();
scanf("%d",&x);
}
fclose(stdin); fclose(stdout);
}
Pixiv ID:62843590