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
#include
using namespace std;
int main() {int n;cin >> n;while (n--) {int m;cin >> m;int * A&#61;new int[m&#43;1];//数组要预先设定大小&#xff0c;否则可以使用动态数组&#xff0c;将数据开在堆区int* B &#61; new int[m &#43; 1];for (int i &#61; 1; i <&#61; m; &#43;&#43;i) {//初始化两个动态数组cin >> A[i];}for (int i &#61; 1; i <&#61; m; &#43;&#43;i) {cin >> B[i];}stack sta;int index_A &#61; 1, index_B &#61; 1;for ( index_A ; index_A <&#61; m; &#43;&#43;index_A) {//即完成主线任务&#xff0c;将所有数据打入栈sta.push(A[index_A]);while (sta.top() &#61;&#61; B[index_B]) {//在输入的过程中可能会有输出index_B&#43;&#43;;sta.pop();if (sta.empty())break;}}if (sta.empty())cout <<"Yes" <
2、2其他版本
int n&#61;0;cin >> n;for (int cishu &#61; 0; cishu > m;vector arr;for (int i &#61; 0; i > temp;arr.push_back(temp);}int index &#61; 0;stack sta;//sta.push(arr[index]);//查看他人的思路&#xff0c;模拟首先要思路清晰for (int i &#61; 0; i > temp;if(sta.empty())sta.push(arr[index]);if (sta.top() &#61;&#61; temp) {sta.pop();}else {while (temp !&#61; arr[index]) {//怎么简化边界的考虑sta.push(arr[index]);//index&#43;&#43;;//sta.push(arr[index]);if (index &#61;&#61; arr.size() - 1) { index&#43;&#43;;break;}index&#43;&#43;;}// cout <}
写的极其复杂&#xff0c;而且还存在BUG&#xff1b;
3、关于模拟类题目的思考 首先是思维要简单&#xff0c;思维简单的意思不是要有漏洞&#xff0c;而是思维的步骤简单&#xff0c;考虑问题的主题要单一&#xff0c;要不变&#xff0c;比如第一篇题解&#xff0c;考虑问题的主题一直是把第一个数组全部打入栈&#xff0c;当完成这个目标时&#xff0c;也就可以验证“Yes”或者“No”.
而我的第二篇题解&#xff0c;在思考问题的主题是每次的第二个数组的输入&#xff0c;并且参杂了验证是否为“Yes”或者“No”&#xff0c;导致思维复杂。
总结而言&#xff0c;考虑问题主体明确&#xff0c;才有可能思维简介&#xff0c;写出高效、漂亮的代码。