posts - 195,  comments - 30,  trackbacks - 0

2nd JOJ Cup Online VContest Problem

We all know that bunny is fond of carrots. One cloudy day, he was told that there would be a violenting flood coming soon to destroy the forests. He was scared and after not thinking too much he told himself that he had to escape. He suddenly recalled that there was a temple on the top of the hill and he might shelter there until the flood's past. But unfortunately there was no food for him on the top of the hill, so he had to take his carrots away along with himself. Then he moved to the foot of the hill and stopped. There was only one way for him to get the top of the hill, that is, a long staircase. Given the number of the steps of the staircase, he asked himself:"how many different ways of strides are there for him to get the top of the hill?". Of course, because of his height, he could only stride a limited range of steps. He was smart so much so that he got the answer quickly. Do you know how he did it?

Input Specification

The input consists of several test cases, each of which occupies a line containing M(1<=M<=40) and N(1<=N<=10), where M indicates the number of the steps of the staircase and N indicates the maximal number of steps the bunny can stride once.

Output Specification

Each test case should correspond to a line in the output. Your program should print an integer which is the answer.

Sample Input

4 2
5 4

Sample Output

5
15


题意是一只兔子要到距离为M(单位为1)的地方,它每步最多走N,问有多少种方法。输入M  N 输出r[m][n];


解析:设为r[i][j],表示距离总共i且每次最多走j的方法数(可以没有走出那大小为j的那步,只是允许走那步而已)。

根据最后那一步可能走的长度,r[i-2][j]表示最后那步距离为2.r[i-j][j]表示最后那步距离为j.
建立递推关系r[i][j]=r[i-1][j]+r[i-2][j]+r[i-3][j]+r[i-j][j];
//本人觉得这里特别难想,想到了也觉得无法建立递推关系呀,j不是一直不变吗?
神奇的地方在于可以令r[0][j]=r[1][j]=1;当然还有r[i][1]=1
-----------预处理----
for(j=0;j<n;j++)

       {

              r[0][j]=1;

              r[1][j]=1;

       }

       for(i=0;i<n;i++)

              r[i][1]=1;


---dp----------
 for(i=2;i<m;i++)
    for(j=2;j<n;j++)
    {
     if(i<j)
        r[i][j]=r[i][i]; //这点非常重要
     else 
       for(k=1;k<=j;k++)
        {
   r[i][j]+=r[i-k][j];
        }
    }
------------
r[1][1]=1
r[2][1]=1
r[2][2]=r[2][1]+r[2][2]=2;
r[3][1]=1;
r[3][2]=r[2][2]+r[1][2]=3;
r[3][3]=r[0][3]+r[1][3]+r[2][3]=4;

posted on 2009-07-20 17:19 luis 阅读(523) 评论(0)  编辑 收藏 引用 所属分类: 动态规划

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2013年3月>
242526272812
3456789
10111213141516
17181920212223
24252627282930
31123456

常用链接

留言簿(3)

随笔分类

随笔档案

文章分类

文章档案

友情链接

搜索

  •  

最新评论

阅读排行榜

评论排行榜