3. stack<int> station;
int nextCoach = 1;
bool possible = true;
for (int i = 0; i < n; i++) {
while (!station.empty() && station.top() == nextCoach) {
station.pop();
nextCoach++;
}
if (coaches[i] == nextCoach) {
nextCoach++;
}
else if (!station.empty() && station.top() < coaches[i]) {
possible = false;
break;
}
else {
station.push(coaches[i]);
}
}
if (possible) {
cout << "Yesn";
}
else {
cout << "Non";
}
// Print a blank line after each test case
cout << endl;
}
return 0;
}
MY CODE STACK ADT FOR REQUIREMENT
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
bool can_rearrange_coaches(int n, vector<int> coaches) {
stack<int> stack;
int i = 0;
4. for (int coach : coaches) {
while (!stack.empty() && stack.top() == i + 1) {
i += 1;
stack.pop();
}
if (coach == i + 1) {
i += 1;
}
else {
stack.push(coach);
}
}
while (!stack.empty() && stack.top() == i + 1) {
i += 1;
stack.pop();
}
return i == n;
}
int main() {
while (true) {
int n;
cin >> n;
if (n == 0) {
break;
}
vector<int> coaches;
while (true) {
int coach;
cin >> coach;
if (coach == 0) {
break;
}
coaches.push_back(coach);
}
if (can_rearrange_coaches(n, coaches)) {
cout << "Yes" << endl;
5. }
else {
cout << "No" << endl;
}
cout << endl;
}
return 0;
}
Question for Reference:
Railroad cars numbered 1,2, ..., n on the right track are to be permuted and moved along on the
left track. A car may be moved directly onto the left track, or it may be shunted onto the siding to
be removed at a later time and placed on the left track. The siding thus operates as a stack, a push
operation moving a car from the right track onto the siding and a pop operation moving the "top"
car from the siding onto the left track. For example, when n = 3, push 1, push 2, move 3, pop 2,
pop 1 arranges them in the order 3, 2,1.
Are any permutations not possible? Yes, for example, 312 is an impossible permutation.
Assume that the train arriving from the direction A has N <= 1000 coaches numbered in
increasing order 1, 2, 3,....N. The chief for train reorganizations must know whether it is possible
to marshal coaches continuing in the same direction so that their order will be. Your job is to
help him to write a program that decides whether it is possible to get the required order of
coaches.
Apply stack ADT in the program.