美团3.25笔试第一题,模拟栈
这道题我的思路一开始是清晰的,但到后面因为调试了太长时间,脑子已经乱了
我的源代码如下
#include <iostream>
#include <algorithm>
#include <stack>
#include <string>
#include <vector>
using namespace std;
int main()
{
int h,x,y,z;
int l = 0;
cin >> h;
stack<int> stackfirst;
vector<int> num;
vector<int> stackbaocun;
vector<int> bijiao;
for (int i = 0; i < h; i++)
{
cin >> x;
for (int j = 0; j < x; j++)
{
cin >> y;
cin >> z;
stackfirst.push(y);
stackbaocun.push_back(y);
bijiao.push_back(z);
}
while (!stackfirst.empty()) {
int temp = stackfirst.top();
cout << temp;
stackfirst.pop();
}
if (stackbaocun[l++] == bijiao[l++])
{
printf("Yes");
}
else {
printf("No");
}
}
/*cout << stackfirst.size() << endl;
cout << bijiao.size() << endl;
while (!stackfirst.empty()) {
int temp = stackfirst.top();
cout << temp;
stackfirst.pop();
}
return 0;
}
chatgpt居然都没有看出来这段代码的用途,所以确实错的很离谱
之后我让chatgpt完善一下这段代码,主要完成功能为根据一个数字1到n的入栈顺序in[]和出栈顺序out[],问这个出入栈顺序是否合法
代码如下:
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> in(n);
vector<int> out(n);
for (int i = 0; i < n; i++) {
cin >> in[i];
}
for (int i = 0; i < n; i++) {
cin >> out[i];
}
stack<int> s;
int i = 0, j = 0;
while (i < n) {
s.push(in[i++]);
while (!s.empty() && s.top() == out[j]) {
s.pop();
j++;
}
}
if (s.empty()) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
return 0;
}
美团的需求需要加入组数,改动后代码如下:
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
void solve()
{
int n;
cin >> n;
vector<int> in(n);
vector<int> out(n);
for (int i = 0; i < n; i++) {
cin >> in[i];
}
for (int i = 0; i < n; i++) {
cin >> out[i];
}
stack<int> s;
int i = 0, j = 0;
while (i < n) {
s.push(in[i++]);
while (!s.empty() && s.top() == out[j]) {
s.pop();
j++;
}
}
if (s.empty()) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
}
int main()
{
int l;
cin >> l;
for (int i = 0; i < l; i++) {
solve();
}
return 0;
}