简单火车车厢重排

#include <iostream>
#include <cmath>
#include <string>
using namespace std;
const int N = 105;
int st[N];

int main()
{
    int n;
    cin >> n;
    int sp[N];
    for (int i = 0; i < n; i++)
        sp[i] = 0;
    cout << "the order of train out:" << endl;
    for (int i = 0; i < n; i++)
        cin >> st[i];
    int pos =0;
    int pos2 = 0;
    for (int i = 1; i <= n; i++)
    {
        if (st[pos] != i) {
            sp[pos2++] = i;
            cout << sp[pos2 - 1] << endl;
        }
        else {
            sp[pos2] = i;
            while (pos2 >= 0 && pos < n&&sp[pos2] == st[pos])
            {
                cout << sp[pos2] << '-' << st[pos] << endl;
                pos2--; pos++;
                //cout << pos2 <<'-'<< pos << endl;
            }
            pos2++;
        }
    }
    while (pos2 >= 0 && pos < n&&sp[pos2] == st[pos])
    {
        cout << sp[pos2] << '-' << st[pos] << endl;
        pos2--; pos++;
    }
    if (pos == n) cout << "ok" << endl;
    system("pause");
    return 0;
}
/*
5
3 4 5 2 1
*/

 

Java火车车厢重排问题是一个经典的数据结构问题,也被称为“火车进站问题”或“车厢重排问题”。该问题的目标是将一列随机顺序的火车车厢按照编号从大到小的顺序重新排列,并且在重排过程中需要使用缓冲铁轨。这个问题可以使用面向对象的方式来解决。 解决这个问题的一种常见方法是使用栈和递归。具体来说,我们可以将每个车厢看作一个对象,并将它们存储在一个栈中。然后,我们可以使用递归来模拟车厢的进出顺序,直到所有车厢都被排列好为止。在递归的过程中,我们需要考虑当前车厢是否可以直接进入目标铁轨,或者是否需要先将其他车厢移动到缓冲铁轨上。 以下是一个简单的Java代码示例,用于解决火车车厢重排问题: ``` import java.util.Stack; public class TrainSorting { private Stack<Integer> station; private Stack<Integer> buffer; private Stack<Integer> output; public TrainSorting() { station = new Stack<Integer>(); buffer = new Stack<Integer>(); output = new Stack<Integer>(); } public void sort(int[] train) { for (int i = train.length - 1; i >= 0; i--) { station.push(train[i]); } sortHelper(train.length); } private void sortHelper(int n) { if (n == 0) { while (!buffer.empty()) { output.push(buffer.pop()); } return; } buffer.push(station.pop()); while (!buffer.empty() && (output.empty() || buffer.peek() < output.peek())) { station.push(buffer.pop()); } sortHelper(n - 1); } public void printResult() { while (!output.empty()) { System.out.print(output.pop() + " "); } } } ``` 在这个示例中,我们首先将所有车厢按照随机顺序压入站台栈中。然后,我们使用sortHelper()方法来递归地将车厢从站台栈移动到输出栈中。在递归的过程中,我们使用缓冲栈来存储当前不能直接移动到输出栈的车厢。最后,我们使用printResult()方法来输出排列好的车厢序列。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值