train2(H1023)

来源:互联网 发布:数据库的应用领域 编辑:程序博客网 时间:2024/05/16 01:04
Problem Description
As we all know the Train Problem I, the boss of the IgnatiusTrain Station want to know if all the trains come instrict-increasing order, how many orders that all the trains canget out of the railway.
Input
The input contains several test cases. Each test casesconsists of a number N(1<=N<=100).The input is terminated by the end of file.
Output
For each test case, you should output how many ways that allthe trains can get out of the railway.
Sample Input
1
2
3
10
Sample Output
1
2
5
16796
此题可以理解为栈的问题:n个数的进栈顺序已定,求出栈的顺序有多少种(用t来表示)。
我的思路如下:
我们不难知道当n=1时,种数t=1;当n=2;我们就可以以1来判断2的位置,显然2可以放在第一位,也可以放在第二位,我们可以标记它在每个位置放的种数:1、1;当n=3时,由2来判断3的位置,当2在第1位时,3可以插在第1、2、3三个位置,当2在第2位时,3只能插在2、3两个位置,那么3在1、2、3三个位置放的种数分别为:1、2、2;同样我们可推出4在1、2、3、4四个位置放的种数分别为:1、3、5、5,以次类推。我们的推理过程是这样的:当我们确定n-1的位置后,n可以放在n-1前一位和后面的所有位置,以这样的思路,我们以此可推出5的每个位置的种数:1、4、9、14、14.我将此列在一起如下:

1 1
1 2 2
1 3 5  5
1 4 9  14 14
1 5 14 28 42 42
. ..  . . .
当n=k时总种为此行数的和,即:
n=1:  t=1
n=2:  t=1+1=2
n=3:  t=1+2+2=5
n=4 :t=1+3+5+5=14
n=5 :t=1+4+9+14+14=42
. ..  . . .
那么我如何计算呢?我们三角数组来存那个三角矩阵,如a[4][2]=3.通过观察我们可以发现:
    a[k][1]=1;
    a[k][i]=a[k][i-1]+a[k-1][i]   (其中1<i<k且k>2);
    a[k][k]=a[k][k-1]   (基中k>1).
有以上三点我们就不难当n=k时t的值了。
其实这个三角矩阵与杨辉三角很相似,大家仿照杨辉三角的求解方法来计算,不过要用到大整数加法,因为当n=100时t为57位数。
我的代码如下:

#include<stdio.h> #include<string.h> int num[201],num1[201],num2[201]; void jia(char *a,char *b,char *c{ int i,j,len,m,n; memset(num2,0,sizeof(num2));    memset(num1,0,sizeof(num1)); memset(num,0,sizeof(num));    m=strlen(a); n=strlen(b);    len=m>n?m:n;    for(i=0,j=m-1;i<m;i++,j--)num[i]=a[j]-'0';    for(i=0,j=n-1;i<n;i++,j--)num1[i]=b[j]-'0';    for(i=0;i<len;i++){ num2[i]+=num[i]+num1[i];        if(num2[i]>9){ num2[i]-=10;            num2[i+1]++; }    }    if(num2[len])len++; for(i=len-1,j=0;i>=0;i--,j++)c[j]=num2[i]+'0';    c[len]=0} int main(){    int m,n,i,j;    char a[201][103],b[201][103],h[200],f[200];    strcpy(b[0],"0");    while(scanf("%d",&m)!=EOF)    {        strcpy(h,"0");        for(i=0;i<=200;i++)strcpy(a[i],"0"); strcpy(a[1],"1");        for(i=2;i<=m;i++)        {            for(j=1;j<i;j++)jia(b[j-1],a[j],b[j]);            strcpy(b[i],b[i-1]);            for(j=1;j<=i;j++)strcpy(a[j],b[j]); } for(i=1;i<=m;i++)        {  jia(a[i],h,f);            strcpy(h,f); } puts(h); }    return 0;}//这种方法不是最简单的方法,要想找更简单的方法,就往百度上找一找!

原创粉丝点击