lzmagic  
1/4桶水荡漾
日历
<2008年10月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678
统计
  • 随笔 - 7
  • 文章 - 0
  • 评论 - 0
  • 引用 - 0

导航

常用链接

留言簿

随笔分类

随笔档案

搜索

  •  

最新评论

阅读排行榜

评论排行榜

 

Description

栈是常用的一种数据结构,有n个元素在栈顶端一侧等待进栈,栈顶端另一侧是出栈序列。你已经知道栈的操作有两种:push和pop,前者是将一个元素进栈,后者是将栈顶元素弹出。现在要使用这两种操作,由一个操作序列可以得到一系列的输出序列。请你编程求出对于给定的n,计算并输出由操作数序列1,2,…,n,经过一系列操作可能得到的输出序列总数。

Input

就一个数n(0<n<20)。

Output

一个数,即可能输出序列的总数目。

Sample Input

3

Sample Output

5
Solution 1st:
a[i][j] renotes the possible number of the previous j sequences with n = i
(we set a[k][0] = 1 (0 < k <= n), which implies NULL is thought of one possible sequence)
we init that a[1][1] = a[1][0] = 1;
yeild:
a[i][0] = a[i - 1][0];
a[i][j] = a[i][j - 1] + a[i - 1][j]; (1 <= j <= i - 1)
a[i][i] = a[i][i - 1];
the answer wo want to get is a[n][n].

 1#include<iostream>
 2using namespace std;
 3
 4#define MAXN 20
 5
 6int main()
 7{
 8    // init
 9    int a[MAXN][MAXN];
10    a[1][1= a[1][0= 1;
11
12    // input the total number pushed into the stack(0 < n && n < 20)
13    int n, i, j;
14    cin >> n;
15
16    // run
17    for(i = 2; i <= n; i++)
18    {
19        a[i][0= a[i - 1][0];
20        for(j = 1; j <= i - 1; j++)
21        {
22            a[i][j] = a[i][j - 1+ a[i - 1][j];
23        }

24        a[i][j] = a[i][j - 1];
25    }

26
27    // ouput the number of possible sequences poped from the stack
28    cout << a[n][n] << endl;
29    
30    return 0;
31}

Solution 2nd:
denote a[n] the number of possible sequences poped from the stack,
denote i the number of the set si poped before the first number pushed '1' poped, 
and denote i the number of the set sj poped after the first number pushed '1' poped,
then we can easily get the conlusion that no number in seti is bigger than any number in setj,
we can depart the sequence into two part and caculate them respectively,
hence the possible number is a[i] * a[j] (0 <= i <= n - 1), i.e.
      a[n] = a[0]*a[n - 1] + a[1]*a[n - 2] + …… + a[n - 2]*a[1] + a[n - 1]*a[0]

 1#include<iostream>
 2using namespace std;
 3
 4#define MAXN 20
 5
 6int main()
 7{
 8    int a[MAXN];
 9    a[0] = 1;
10    int n, i, j;
11    cin >> n;
12    for(i = 1; i <= n; i++)
13    {
14        for(a[i] = 0, j = 0; j < i; j++)
15            a[i] += a[j] * a[i - 1 - j];
16    }
17    for(i = 1; i <= n; i++)
18        cout << "a[" << i << "] = " << a[i] << endl;
19    return 0;
20}

Solution 3id:

This is Catalan Number :
a[n] = a[0]*a[n - 1] + a[1]*a[n - 2] + …… + a[n - 2]*a[1] + a[n - 1]*a[0]
a[n] = C(n , 2 * n) / (n + 1)
posted on 2008-04-27 14:56 lzmagic 阅读(52) 评论(0)  编辑 收藏 引用 所属分类: practising

标题  
姓名  
主页
验证码 *
内容(提交失败后,可以通过“恢复上次提交”恢复刚刚提交的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
[使用Ctrl+Enter键可以直接提交]
相关链接:
网站导航:



 
Copyright © lzmagic Powered by: 博客园 模板提供:沪江博客