c ++ statistics stack

Title Description

1 ~ n sequentially stack, a stack of different statistical manner

Is commonly used as a stack data structure, there are n elements in the stack so that the top side of the stack into the waiting, the stack is popped to the top side of the other sequence. You already know that there are two stacks of operation • species: push and pop, the former is an element onto the stack, which is the top element will pop up. Use now both operations, a sequence of operations can be obtained by a series of output sequence. Please program determined for a given n, and outputs calculated by the operand sequence 1,2, ..., n, the total number of the output sequence may be obtained through a series of operations.

Entry

An integer n (1 <= n <= 15)

Export

An integer, i.e., the total number of possible output sequences.

Sample input

3

Sample Output

5

Source Code

#include <iostream>
#include <stdio.h>
using namespace std;
int n;
int t;
int s[20],top;
int opt[20];
int l = 0;
int ans = 0;
void dfs(int u)
{
    if (l == n)
    {
        ans ++;
        return ;
    }
    if (t <= n)//判断是否所有数据都已经入栈 如果有数据没有入栈,则执行
    {
        top ++;//栈顶指针向上移
        s[top] = t;//把t入栈
        t ++;//栈里面的数量 +1   或者已使用的数量 +1
        dfs(u + 1);//递归找下一个数字
        top --;//出栈
        t --;//栈里面的数量 -1
    }
    if (top >= 1)
    {
        int tmp = s[top];
        l ++;
        opt[l] = s[top];
        top --;
        dfs(u + 1);
        top ++;
        s[top] = tmp;
        l --;
    }
}
int main()
{
    cin >> n;
    t = 1;
    top = 0;
    dfs(1);
    cout << ans << endl;
}

(Notes continued)

Guess you like

Origin www.cnblogs.com/LJA001162/p/11334914.html