hdu2018 (递归,记忆化递归)

来源:互联网 发布:考研网络辅导班 编辑:程序博客网 时间:2024/04/30 23:57

这里写图片描述
很水的题,但好歹带我入门了一点动态规划?不,是递归。都没推出递推关系啦,可惜题目的数据太水啦,递归和保存已有的再递归 时间都看不出来差别。。。。。

纯递归,怎么理解了:就是 你想啊 每下一刻奶牛的数量等于上一刻已有数量加上要增加的数量,而由题意每四秒后刚出生的小母牛就可以长大成能生出小母牛的大母牛,要增加的数量等于当前三秒前,因为当前的三秒前到当前就是四秒,就会增加一个能生小母牛的大母牛。

#include<stdio.h>int cow(int n){    if(n<=4)    return n;    else    return cow(n-1)+cow(n-3);}int main(){    int n,m;    while(scanf("%d",&n)&&n)    {       m=cow(n);       printf("%d\n",m);    }    return 0;}

加一个记忆已经算过的点,然并暖 ,这题数据太水!

#include<iostream>#include<cstdio>#include<cstring>using namespace std;int a[60],n;int cow(int n){    if(a[n]>0)        return a[n];    else    {        a[n]=cow(n-1)+cow(n-3);        return a[n];    }}int main(){   #ifdef yexiaoju   freopen("Untitled2.txt","r",stdin);   #endif // yexiaoju   memset(a,0,sizeof(a));   for(int i=1;i<=4;i++) a[i]=i;   while(scanf("%d",&n)&&n)  {      int num=cow(n);      printf("%d\n",num);  }  return 0;}
1 0
原创粉丝点击