火车车厢重新排列问题

火车车厢重新排序——栈的应用


一、需求分析

需求分析


二、算法设计

算法设计


实验结果

实验结果


三、代码模块

#include <iostream>
#include <stack>
#include <vector>
#include <windows.h>
using namespace std;
int main(){
    int n,m;
    cout<<"please input the number of train:"<<endl;
    cin>>n;
    int *train = new int[n * sizeof(int)];
    cout<<"input train number:"<<endl;
    for(int i=0;i<n;i++){
        cin>>m;
        train[i]=m;
    }
    vector< stack<int> > v;
    int count=1,k=0,total=0;
    bool suc=false;
    while(count<=n){
        if(k<n && train[k] == count){
            cout<<train[k]<<" will leave!"<<endl;;
            count++;
            k++;
        }
        else{
            if(k<n){
                int pos=1;
                for(auto &i:v){
                    if( i.empty()||train[k]<i.top()){
                        i.push(train[k]);
                        cout<<train[k]<<" has been pushed in stack["<<pos<<"]!"<<endl;
                        suc=true;
                        k++;
                        break;
                    }
                    pos++;
                }

                if(!suc){
                    stack<int> st;
                    st.push(train[k]);
                    v.push_back(st);
                    cout<<"here will build a new stack and "<<train[k]<<" will be pushed in!"<<endl;
                    k++;
                    total++;
                }
                suc=false;
            }
            for (int i = 0; i < v.size(); ++i){
                while(!v[i].empty() && v[i].top()==count){
                    cout<<v[i].top()<<" will be poped from stack["<<i+1<<"] and leave!"<<endl;
                    v[i].pop();
                    count++;
                }
            }
        }
    }
    for (int i = 1; i <= n; ++i)
    {
        cout<<i<<' ';
    }
    cout<<"use "<<total<<" stack"<<endl;
    delete []train;
    system("pause");
    return 0;
}

希望各位有什么好的想法,可以在评论区多多留言,小白衷心感谢各位的意见~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值