1、题目
给出两个序列 pushed 和 poped 两个序列,其取值从 1 到 n(n\le100000)n(n≤100000)。已知入栈序列是 pushed,如果出栈序列有可能是 poped,则输出 Yes
,否则输出 No
。
注意:可能两个字,即每次操作有可能是直接出栈,还有可能是入栈再出栈
输入格式:
第一行一个整数 qq,询问次数。
接下来 qq 个询问,对于每个询问:
第一行一个整数 nn 表示序列长度;
第二行 nn 个整数表示入栈序列;
第二行 nn 个整数表示出栈序列;
输出格式:
对于每个询问输出答案。
输入样例:
2
5
1 2 3 4 5
5 4 3 2 1
4
1 2 3 4
2 4 1 3
输出样例:
Yes
No
1、2对题目的理解:
即不是简单的全部入栈,然后出栈,不过,只要在这个基础上,验证每次数据入栈之后有没有出栈的操作即可。
2、题解:
2、1给出正确版本
#include <iostream>
#include<stack>
using namespace std;
int main() {
int n;
cin >> n;
while (n--) {
int m;
cin >> m;
int * A=new int[m+1];//数组要预先设定大小,否则可以使用动态数组,将数据开在堆区
int* B = new int[m + 1];
for (int i = 1; i <= m; ++i) {//初始化两个动态数组
cin >> A[i];
}
for (int i = 1; i <= m; ++i) {
cin >> B[i];
}
stack<int> sta;
int index_A = 1, index_B = 1;
for ( index_A ; index_A <= m; ++index_A) {//即完成主线任务,将所有数据打入栈
sta.push(A[index_A]);
while (sta.top() == B[index_B]) {//在输入的过程中可能会有输出
index_B++;
sta.pop();
if (sta.empty())break;
}
}
if (sta.empty())cout << "Yes" << endl;
else cout << "No" << endl;
}
}
2、2其他版本
int n=0;
cin >> n;
for (int cishu = 0; cishu < n; ++cishu) {
int m=0;
cin >> m;
vector<int> arr;
for (int i = 0; i < m; ++i) {
int temp;
cin >> temp;
arr.push_back(temp);
}
int index = 0;
stack<int> sta;
//sta.push(arr[index]);//查看他人的思路,模拟首先要思路清晰
for (int i = 0; i < m; ++i) {
int temp;
cin >> temp;
if(sta.empty())sta.push(arr[index]);
if (sta.top() == temp) {
sta.pop();
}
else {
while (temp != arr[index]) {//怎么简化边界的考虑
sta.push(arr[index]);
//index++;
//sta.push(arr[index]);
if (index == arr.size() - 1) {
index++;
break;
}
index++;
}
// cout << sta.top() << endl;
}
if (index == arr.size()) {
cout << "No" << endl;
break;
}
}
if (sta.empty())cout << "Yes" << endl;
}
}
写的极其复杂,而且还存在BUG;
3、关于模拟类题目的思考
首先是思维要简单,思维简单的意思不是要有漏洞,而是思维的步骤简单,考虑问题的主题要单一,要不变,比如第一篇题解,考虑问题的主题一直是把第一个数组全部打入栈,当完成这个目标时,也就可以验证“Yes”或者“No”.
而我的第二篇题解,在思考问题的主题是每次的第二个数组的输入,并且参杂了验证是否为“Yes”或者“No”,导致思维复杂。
总结而言,考虑问题主体明确,才有可能思维简介,写出高效、漂亮的代码。