02-线性结构4 Pop Sequence(25 分)
Given a stack which can keep M numbers at most. Push N numbers in the order of 1, 2, 3, ..., N and pop randomly. You are supposed to tell if a given sequence of numbers is a possible pop sequence of the stack. For example, if M is 5 and N is 7, we can obtain 1, 2, 3, 4, 5, 6, 7 from the stack, but not 3, 2, 1, 7, 5, 6, 4.
Input Specification:
Each input file contains one test case. For each case, the first line contains 3 numbers (all no more than 1000): M (the maximum capacity of the stack), N(the length of push sequence), and K (the number of pop sequences to be checked). Then K lines follow, each contains a pop sequence of N numbers. All the numbers in a line are separated by a space.
Output Specification:
For each pop sequence, print in one line "YES" if it is indeed a possible pop sequence of the stack, or "NO" if not.
Sample Input:
5 7 5
1 2 3 4 5 6 7
3 2 1 7 5 6 4
7 6 5 4 3 2 1
5 6 4 3 7 2 1
1 7 6 5 4 3 2
Sample Output:
YES NO NO YES
No
参考代码(未评分):(以下是我严重不满意的代码,运用了多重选择和循环,差点没看懂自己写的东西,有待改善。)
#include<iostream>
using namespace std;
const int stacksize =1024;
struct snode
{
int data[stacksize];
int top=-1;
};
void push(snode *p, int x)
{
if (p->top ==stacksize - 1)
cout << "栈已满" << endl;
else
{
p->data[++(p->top)] = x;
}
}
int pop(snode *p)
{
if (p->top == -1)
return 0;
else
{
p->top--;
return p->data[p->top + 1];
}
}
void main()
{
int M, N, K;
int index, Y;
int q,x;
snode stack;
snode *pp = &stack;
cin >> M >> N >> K;
int *a = new int[N*K];
int *b = new int[2 * N+1];
for (int m = 0; m <= N ; m++)
{
b[m] = m;
}
for (int i = 0; i < K; i++)
{
for (int j = 0; j < N; j++)
{
int k;
cin >> k;
a[j+i*N] = k;
}
}
for (int i = 0; i < K; i++)
{
bool flag = 1;
index = 0;
Y = 1;
int count = 0;
int j = 0;
for (int m = N + 1; m <= 2 * N; m++)
{
b[m] = 0;
}
for (int c = 0; c < N; c++)//结束内循环就要得出判断
{
while(index < Y)//当index<Y,将index+1`Y的值压入栈,注意栈的空间,抛出栈顶元素,和Y是否相等,若相等,更新index和Y的值,继续执行操作
{
for (q=index + 1; q<=a[j+i*N]; q++)//入栈模拟
{
if (count>= M)//应结束入栈操作
{
break;
}
else
{
if (b[q + N] == 0)
{
push(pp, q);
b[q + N] = 1;
count++;
}
else
continue;
}
}
x = pop(pp);
count--;
if (x != a[j + i*N])
{
flag = 0;
break;
}
else//如果栈顶和当前值相等,则将当前值设为index,下一个数设为Y。需要比较index和Y的大小,来确定需要执行的操作。
{
index = a[j + i*N];
if (j + 1 < N)
{
j++;
Y = a[j + i*N ];
}
else
break;
continue;
}
}
while(index>Y)
{
x = pop(pp);
count--;
if (x != Y)
{
flag = 0;
break;
}
else
{
index = Y;
if (j + 1 < N)
{
j++;
Y = a[j + i*N ];
}
else
break;
continue;
}
}
}
if (flag == 1)
cout << "Yes" << endl;
else
cout << "No" << endl;
}
delete[]a;
system("pause");
}