NOJ [1138] Honeycomb

  • 问题描述
  • Miku is separated with her friends,so she should go to search for them.But she should pass a big diamond honeycomb.She can only go down and get into adjacent room.As shown in graph.For example,if the edge length of diamond honeycomb is 4,the number of rooms is 1,2,3,4,3,2,1 from top to bottom.She should get into the bottom room to get out.

  • 输入
  • Input until EOF.
    Tnput a positive integer N(1<N<=30) means the edge length of diamond honeycomb.
  • 输出
  • You should calculate the number of different routes she can get out.

    这题,不难看出是DP,虽然有现成的数学公式可以用,但这里给出DP的做法

    首先来看,输入一个n,总共多少层?
    答案是2*n-1
    1 2 3 ... n n+1...2*n-1
    好的,接下来分析状态转移方程
    先看上n层,对于不是边缘的蜂巢来说,当前其走法是上一层与它相邻的两个蜂巢的走法之和,对于是边缘的蜂巢,那么就是上一层与它相邻的蜂巢的走法
    再看下面的n-1层, 当前其走法是上一层与它相邻的两个蜂巢的走法之和。
    上n层,第i层有i个蜂巢
    下n-1层,第i层有2*n-i层

    由上面的分析,我们不难得出如下的状态转移方程
      
    i<=n时
    dp[i][j]=dp[i-1][j] (j==1 )
    dp[i][j]=dp[i-1][j-1] (j==i)
    dp[i][j]=dp[i-1][j-1]+dp[i-1][j]
    i>n时
    dp[i][j]=dp[i-1][j-1]+dp[i-1][j]
    #include<stdio.h>
    #include<string.h>
    
    long long  dp[40][40];
    
    int main()
    {
    	int n;
    	while(~scanf("%d",&n))
    	{
    		int i,j;
    		memset(dp,0,sizeof(dp));
    		dp[1][1]=1;
    		for(i=2;i<=n;i++)
    		  for(j=1;j<=i;j++)
    		    if(j==1)
    		       dp[i][j]=dp[i-1][j];
                else if(j==i)
                   dp[i][j]=dp[i-1][i-1];
                else
                   dp[i][j]=dp[i-1][j-1]+dp[i-1][j];
             for(i=n+1;i<=2*n-1;i++)
               for(j=1;j<=2*n-i;j++)
                  dp[i][j]=dp[i-1][j+1]+dp[i-1][j];
             printf("%lld\n",dp[2*n-1][1]);
    	}
    	return 0;
    }




你可能感兴趣的:(NOJ [1138] Honeycomb)