火车车厢重排队列c++
时间: 2023-10-18 17:04:25 浏览: 130
火车车厢重排队列问题可以使用栈来解决。具体步骤如下:
1. 读入原始车厢序列,保存在一个数组中。
2. 定义一个栈,用于辅助重排车厢。
3. 从左到右依次遍历原始车厢序列,对于每一个车厢,执行以下操作:
a. 若当前车厢是目标车厢序列中下一个要进站的车厢,则直接将其进站。
b. 若当前车厢不是目标车厢序列中下一个要进站的车厢,则将其压入栈中。
4. 当遍历完整个原始车厢序列后,如果栈不为空,则依次将栈中的车厢出栈并进站,直到栈为空。
5. 如果栈已经为空且进站序列中的车厢数量等于原始车厢序列中的车厢数量,则说明重排成功,返回true;否则返回false。
以下是C++代码实现:
```c++
#include <iostream>
#include <stack>
using namespace std;
bool checkOrder(int n, int ori[], int tar[]) {
stack<int> s;
int i = 0, j = 0; // i指向原始车厢序列,j指向目标车厢序列
while (i < n) {
if (ori[i] == tar[j]) { // 当前车厢是目标车厢序列中下一个要进站的车厢
i++;
j++;
} else if (!s.empty() && s.top() == tar[j]) { // 栈顶车厢是目标车厢序列中下一个要进站的车厢
s.pop();
j++;
} else { // 将当前车厢压入栈中
s.push(ori[i]);
i++;
}
}
while (!s.empty() && s.top() == tar[j]) { // 栈中剩余车厢出栈并进站
s.pop();
j++;
}
return j == n; // 进站序列中的车厢数量等于原始车厢序列中的车厢数量,则重排成功
}
int main() {
int n;
cin >> n;
int ori[n], tar[n];
for (int i = 0; i < n; i++) {
cin >> ori[i];
}
for (int i = 0; i < n; i++) {
cin >> tar[i];
}
if (checkOrder(n, ori, tar)) {
cout << "Possible" << endl;
} else {
cout << "Impossible" << endl;
}
return 0;
}
```