超级楼梯 HDU - 2041
有一楼梯共M级,刚开始时你在第一级,若每次只能跨上一级或二级,要走上第M级,共有多少种走法?
Input
输入数据首先包含一个整数N,表示测试实例的个数,然后是N行数据,每行包含一个整数M(1<=M<=40),表示楼梯的级数。Output对于每个测试实例,请输出不同走法的数量
Sample Input2
2
3Sample Output1
2
只需要举几个例子:
1;
1
2 :
1 1
3:
1 2
1 1 1
4:
1 1 1 1
1 1 2
1 2 1
5:
1 1 1 1 1
1 1 1 2
1 1 2 1
1 2 1 1
1 2 2
6:
1 1 1 1 1 1
1 1 1 1 2
1 1 1 2 1
1 1 2 1 1
1 1 2 2
1 2 1 1 1
1 2 1 2
1 2 2 1
可以发现规律:a[i]=a[i-1]+a[i-2];
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int a[45];
int main(int argc, char** argv) {
int n,m;
cin>>n;
memset(a,0,sizeof(a));
a[1]=0;
a[2]=1;
a[3]=2;
for(int i=4;i<=40;i++){
a[i]=a[i-1]+a[i-2];
}
while(n--){
cin>>m;
printf("%d\n",a[m]);
}
return 0;
}
母牛的故事 HDU - 2018
有一头母牛,它每年年初生一头小母牛。每头小母牛从第四个年头开始,每年年初也生一头小母牛。请编程实现在第n年的时候,共有多少头母牛?
Input
输入数据由多个测试实例组成,每个测试实例占一行,包括一个整数n(0<n<55),n的含义如题目中描述。
n=0表示输入数据的结束,不做处理。Output对于每个测试实例,输出在第n年的时候母牛的数量。
每个输出占一行。
Sample Input2
4
5
0Sample Output2
4
6
题目思路:
排出前几年牛的情况
第一年 第二年 第三年 2 3 4
第四年 第五年 第六年 6 9 13
第七年 第八年 第九年 19 28 41
第一年牛会生一头小牛,所以第一年结束时有2头,第二年结束时有3头,第三年结束时有4头,这没有问题吧第四年起,第一年的小牛可以再生小牛,所以为6,第五年时,第二年的小牛也可以再生小牛,所以为9,第六年时,第三年的小牛也可以再生小牛,规律是:当年的牛的数量等于三年前的牛的数量加前一年的牛的数量(因为3年前的牛都可以再生小牛,小牛是多出来的)
会发现规律:a[i]=a[i-1]+a[i-3];
其实就是前一年牛的数量加上四年前的牛的数量(四年后都成了成为了大奶牛)
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int a[60];
int main(int argc, char** argv) {
memset(a,0,sizeof(a));
int n;
a[1]=1,a[2]=2,a[3]=3,a[4]=4;
for(int i=5;i<=55;i++){
a[i]=a[i-1]+a[i-3];
}
while(cin>>n&&n){
cout<<a[n]<<endl;
}
return 0;
}