判断出栈序列
题目信息输入输出测试样例
解答
题目信息
判断:指定的序列能否仅由 入栈 和 出栈 操作得到。
输入
有若干组数据输入 每组数据中,第一行为两个个整数 n 和 m。n 表示需要依次从 1~n 入栈,m 表示这组数据有 m 个出栈序列需要判断,当 n=0 且 m=0 时停止。 接下来有行,每行表示一个出栈序列
输出
对每一个出栈序列,如果能正常出栈,则输出 Yes,否则输出 No。
测试样例
测试样例1
5 2
1 2 3 4 5
5 4 1 2 3
6 2
6 5 4 3 2 1
3 2 5 6 4 1
0 0
Yes
No
Yes
Yes
测试样例2
5 2
1 2 3 4 5
5 4 1 2 3
6 1
6 5 4 3 2 1
0 0
Yes
No
Yes
解答
#include <cstring>
#include <iostream>
#include <vector>
#include <stack>
using namespace std
;
bool IsPopOrder(const vector
<int>& Push
, const vector
<int>& Pop
)
{
if (Push
.size() != Pop
.size())
{
return false;
}
stack
<int> temp
;
int PushIndex
= 0;
int PopIndex
= 0;
int Size
= Pop
.size();
while (PopIndex
< Size
)
{
for (; PushIndex
< Size
; PushIndex
++)
{
if (Push
[PushIndex
] == Pop
[PopIndex
])
{
PopIndex
++;
PushIndex
++;
break;
}
temp
.push(Push
[PushIndex
]);
}
if (!temp
.empty() && temp
.top() != Pop
[PopIndex
])
{
for (; PushIndex
< Size
; PushIndex
++)
{
if (Push
[PushIndex
] == Pop
[PopIndex
])
{
PopIndex
++;
PushIndex
++;
break;
}
temp
.push(Push
[PushIndex
]);
}
}
else if (!temp
.empty())
{
temp
.pop();
PopIndex
++;
}
if (!temp
.empty() && PushIndex
>= Size
&& temp
.top() != Pop
[PopIndex
])
{
return false;
}
else
{
while (!temp
.empty() && temp
.top() == Pop
[PopIndex
])
{
temp
.pop();
PopIndex
++;
}
}
}
if (temp
.empty() && PushIndex
>= Size
)
{
return true;
}
return false;
}
int main()
{
int op
= 1;
while (op
++)
{
int n
, m
;
cin
>> n
>> m
;
if (n
== 0 && m
== 0)
{
return 0;
}
if (op
> 2)
{
cout
<< endl
;
}
vector
<int> push
;
for (int i
= 1; i
<= n
; i
++)
{
push
.push_back(i
);
}
for (int i
= 0; i
< m
; i
++)
{
vector
<int> pop
;
for (int j
= 0; j
< n
; j
++)
{
int tmp
;
cin
>> tmp
;
pop
.push_back(tmp
);
}
if (IsPopOrder(push
, pop
))
{
cout
<< "Yes" << endl
;
}
else
{
cout
<< "No" << endl
;
}
}
}
}