AcWing train into the stack

AcWing train into the stack

Description

  • There are n train is arriving and then the station, but the train only every section 1, and that is the front.

    This n train order from 1 to n from the east turn left stop, this station is a north-south direction, although it is infinitely long, but unfortunately is a dead end, and only one site Track, trains can only go backwards from the West and each train must stop, last out.

    That the train station is actually equivalent to a stack, each time allowing the train head right into the stack, the stack or let the train out of the station.

    Now it's 20 possible solutions before the stack by "dictionary order" output.

Input

  • Enter an integer n, indicating the number of trains.

Output

  • According to 20 kinds of answers "dictionary order" output before each line one of no spaces.

Data Size

  • 1≤n≤20

Sample Input

3

Sample Output

123
132
213
231
321

answer:

  • Search (with stack simulation).
  • If you do not see a problem up is no brain found it burst a direct WA(This is how I am)
  • Note that this search is based on the nature of the "stack" of!
  • So in the face every state, there are the following two options:
    1. The next number onto the stack
    2. The top of the stack pop
  • So after 2 * n operations, so the elements certainly have popped up.
#include <iostream>
#include <cstdio>
#include <stack>
#define N 25
using namespace std;

int n, flag, cnt;
int a[N];
stack<int> stk;

void dfs(int step, int num)
{
    if(flag) return;
    if(step > 2 * n)
    {
        cnt++;
        if(cnt == 20) flag = 1;
        for(int i = 1; i <= 2 * n; i++)
            if(a[i]) cout << a[i];
        cout << endl;
        return;
    }
    if(stk.size())
    {
        int t =stk.top();
        a[step] = t;
        stk.pop();
        dfs(step + 1, num);
        stk.push(t);
        a[step] = 0;
    }
    if(num <= n)
    {
        stk.push(num);
        dfs(step + 1, num + 1);
        stk.pop();
    }
}

int main()
{
    cin >> n;
    dfs(1, 1);
    return 0;
}

Guess you like

Origin www.cnblogs.com/BigYellowDog/p/11300729.html