问题描述
小F正在玩一个套碗的游戏,每个碗都有一个编号,从1到n,它们从大到小被套在一根木棍上。小F只能从木棍上取最上面的碗,每次只能取一个。现在你需要判断给定的取碗顺序是否可行。如果可行,那么返回1,否则返回0。
例如,对于2个碗,取碗的顺序可以是 2 1 或 1 2,这两种顺序都是合法的。而对于3个碗,给定顺序 3 1 2 不可能通过合法操作实现,因此该顺序不可行。
测试样例
样例1:
输入:
M = 2, a = [1, 2]
输出:1
样例2:
输入:
M = 3, a = [3, 1, 2]
输出:0
样例3:
输入:
M = 4, a = [1, 3, 2, 4]
输出:1
#include <iostream>
#include <stack>
#include <string>
#include <vector>
using namespace std;
int solution(int M, std::vector<int> &a) {
stack<int> stk;
int current = 1; // 从编号1开始压入
for (int i = 0; i < M; ++i) {
int target = a[i];
// 如果栈为空,或者栈顶不是目标,则继续压栈
while (current <= M && (stk.empty() || stk.top() != target)) {
stk.push(current++);
}
// 如果栈顶不是目标,则表示目标在栈底下,无法取出
if (stk.top() != target)
return 0;
// 弹出栈顶
stk.pop();
}
return 1;
}
int main() {
std::vector<int> a1 = {1, 2};
std::cout << (solution(2, a1) == 1) << std::endl;
std::vector<int> a2 = {3, 1, 2};
std::cout << (solution(3, a2) == 0) << std::endl;
std::vector<int> a3 = {1, 3, 2, 4};
std::cout << (solution(4, a3) == 1) << std::endl;
return 0;
}