题意:第1年有1头奶牛,每年生一头奶牛,新生的奶牛从生下来的第四年(包括生下来那年)也开始每年一头奶牛。
问第n年有多少头奶牛。
思路:最容易想到的。。递推一下。。。dp[i] = dp[i-1] + dp[i-3] (注意初始化不是一个dp[1]=1,而是dp[1..4]=1..4)
递推代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
/* *********************************************** Author :111qqz Created Time :2016年07月27日 星期三 13时19分17秒 File Name :code/hdu/2018.cpp ************************************************ */ #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <vector> #include <queue> #include <set> #include <map> #include <string> #include <cmath> #include <cstdlib> #include <ctime> #define fst first a#define sec second #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define ms(a,x) memset(a,x,sizeof(a)) typedef long long LL; #define pi pair < int ,int > #define MP make_pair using namespace std; const double eps = 1E-8; const int dx4[4]={1,0,0,-1}; const int dy4[4]={0,-1,1,0}; const int inf = 0x3f3f3f3f; const int N=60; int n; LL dp[N]; int main() { #ifndef ONLINE_JUDGE freopen("code/in.txt","r",stdin); #endif dp[1] = 1; dp[2] = 2; dp[3] = 3; dp[4] = 4; for ( int i = 5 ; i < N ; i++) { dp[i] = dp[i-1] + dp[i-3]; } // for ( int i = 0 ; i < N; i++) // cout<<"i:"<<i<<" dp[i]:"<<dp[i]<<endl; while (scanf("%d",&n)!=EOF) { if (n==0) break; printf("%lld\n",dp[n]); } #ifndef ONLINE_JUDGE fclose(stdin); #endif return 0; } |
也可以考虑记忆化嘛
理论上应该是所有的dp都可以写成记忆化。。。?
记忆化的好处是不用考虑什么边界的问题。。。坏处是。。可能爆栈。。。。。
记忆化代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
/* *********************************************** Author :111qqz Created Time :2016年07月27日 星期三 13时19分17秒 File Name :code/hdu/2018.cpp ************************************************ */ #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <vector> #include <queue> #include <set> #include <map> #include <string> #include <cmath> #include <cstdlib> #include <ctime> #define fst first #define sec second #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define ms(a,x) memset(a,x,sizeof(a)) typedef long long LL; #define pi pair < int ,int > #define MP make_pair using namespace std; const double eps = 1E-8; const int dx4[4]={1,0,0,-1}; const int dy4[4]={0,-1,1,0}; const int inf = 0x3f3f3f3f; const int N=60; int n; LL dp[N]; LL cal( int n) { if (dp[n]!=-1) return dp[n]; return dp[n] = cal(n-1) + cal(n-3); } int main() { #ifndef ONLINE_JUDGE freopen("code/in.txt","r",stdin); #endif ms(dp,-1); dp[1] = 1; dp[2] = 2; dp[3] = 3; dp[4] = 4; while (scanf("%d",&n)!=EOF) { if (n==0) break; printf("%lld\n",cal(n)); } #ifndef ONLINE_JUDGE fclose(stdin); #endif return 0; } |
说点什么
您将是第一位评论人!