Determine la secuencia de la pila
Información del tema
Juicio: si la secuencia especificada se puede obtener solo mediante las operaciones de apilado y estallido.
Entrada:
Hay varios grupos de entrada de datos En
cada grupo de datos, la primera línea son dos números enteros n y m. n significa que debe insertarse en la pila secuencialmente de 1 an, y m significa que este grupo de datos tiene m secuencias emergentes para ser juzgadas, y se detiene cuando n = 0 ym = 0.
Hay líneas a continuación, cada línea representa una secuencia emergente
Salida:
Para cada secuencia de pop, si la pila se puede desplegar normalmente, emita Sí, de lo contrario, envíe No.
Entrada de prueba | Espere salida | |
---|---|---|
Caso de prueba 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 |
Caso de prueba 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 |
responder
#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;
}
//123456
//325641
stack<int> temp;
int PushIndex = 0;//这个用来遍历原栈
int PopIndex = 0;//这个用来遍历后来的栈
int Size = Pop.size();//6
while (PopIndex < Size)
{
//相当于在后来的栈中一个一个在原栈中去对应
for (; PushIndex < Size; PushIndex++)
{
//这个for循环是用来寻找到原栈中和现在栈中相等的元素
if (Push[PushIndex] == Pop[PopIndex])
{
PopIndex++;
PushIndex++;
break;
}
temp.push(Push[PushIndex]);//如果没有找到的话就先把原栈存储到temp栈中,用来模拟出入栈这个过程
}//如果这个循环结束了表明要么没有找到相同的,把所有该存入的值都存好了,要么就是找到相同的值跳出来
if (!temp.empty() && temp.top() != Pop[PopIndex])
{
//如果temp不是空的,且其顶端存储的值不等于后来刚刚存进去的这个值
for (; PushIndex < Size; PushIndex++)
{
if (Push[PushIndex] == Pop[PopIndex])
{
PopIndex++;
PushIndex++;
break;
}
temp.push(Push[PushIndex]);
}
}
else if (!temp.empty())
{
//如果下一个值相同的话则弹出temp中顶端的值,同时可以读下一个后来的栈的值了
temp.pop();
PopIndex++;
}
if (!temp.empty() && PushIndex >= Size && temp.top() != Pop[PopIndex])
{
//如果此时之前的栈已经被遍历结束 且 temp中剩余的那个不等于后来的那个值 且temp剩余东西了
return false;
}
else
{
while (!temp.empty() && temp.top() == Pop[PopIndex])
{
//不断倒着弹出相同的值
temp.pop();
PopIndex++;
}
}
}
if (temp.empty() && PushIndex >= Size)
{
//用来模拟的temp全部清空了,且原栈的遍历已经结束即成功的匹配上了
return true;
}
return false;
}
int main()
{
freopen("E://test.txt", "r", stdin);
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;
}
}
}
}