火車進站

描述

給定一個正整數N表明火車數量,0<N<10,接下來輸入火車入站的序列,一共N輛火車,每輛火車以數字1-9編號。要求以字典序排序輸出火車出站的序列號。ios

知識點
運行時間限制 0M
內存限制 0
輸入

有多組測試用例,每一組第一行輸入一個正整數N(0<N<10),第二行包括N個正整數,範圍爲1到9。測試

輸出

輸出以字典序排序的火車出站序列號,每一個編號以空格隔開,每一個輸出序列換行,具體見sample。spa

樣例輸入 3 1 2 3
樣例輸出

1 2 3 1 3 2 2 1 3 2 3 1 3 2 1blog

 

隱含條件,這個題目中的火車站是個棧,前面的沒出站,後面的來了的話,就把前面的堵在裏面了。排序

仔細思考幾個回合,便可發現其中規律。ip

本題用dfs解決,代碼以下:內存

#include<iostream>
#include<stack>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;

void display(vector<int> arr)
{
    for(unsigned int i=0; i<arr.size()-1; i++)
    {
        cout<<arr[i]<<' ';
    }
    cout<<arr[arr.size()-1]<<endl;
}

bool comp12(vector<int> v1, vector<int> v2)
{
    int n= v1.size();
    for(int i=0; i<n; i++)
    {
        if(v1[i]!=v2[i])
        {
            return v1[i]<v2[i];
        }
    }
    return true;
}

void solve(int count, int *input, int N, stack<int> &stk, vector<int> &arr, vector<vector<int> > &arrs)
{
    if(count==N-1)
    {
        //the last
        arr.push_back(input[count]);

        int stksz = stk.size();
        while(!stk.empty())
        {
            int tmp = stk.top();
            stk.pop();
            arr.push_back(tmp);
        }


        arrs.push_back(arr);



        for(int i=0; i<stksz; i++)
        {
            int tmp = arr.back();
            stk.push(tmp);
            arr.pop_back();
        }
        arr.pop_back();//pop the last
    }
    else
    {
        stk.push(input[count]);
        int stksize = stk.size();
        //cout<<"size"<<stksize<<endl;
        for(int i=0; i<=stksize; i++)
        {
            //cout<<"x"<<i<<endl;
            for(int j=0; j<i; j++)
            {
                int tmp = stk.top();
                //cout<<"top"<<tmp<<endl;
                stk.pop();
                arr.push_back(tmp);
            }
            solve(count+1,  input ,N,stk, arr, arrs);
            for(int j=0; j<i; j++)
            {
                int tmp = arr.back();
                stk.push(tmp);
                arr.pop_back();
            }
        }
        stk.pop();
    }
}

int main()
{
    int N;
    cin>>N;
    int *input;
    input = new int [N];

    for(int i=0; i<N; i++)
    {
        cin>>input[i];
    }

    int count = 0;
    stack<int> stk;
    vector<int> arr;
    vector<vector<int> > arrs;
    solve(count, input, N, stk, arr, arrs);

    sort(arrs.begin(), arrs.end(), comp12);

    for(unsigned int i=0; i<arrs.size(); i++)
    {
        display(arrs[i]);
    }

    delete [] input;

    return 0;
}
相關文章
相關標籤/搜索