首页 > 代码库 > hdu1068【动态规划】

hdu1068【动态规划】

  一道经典的dp。因子中只含2,3,5,7的数字叫做humble number,求第n个丑数。任何新的丑数都是原来的丑数乘以2or3or5or7得来的,由此可以得到新的丑数的转移方程dp[i] = min(dp[a] * 2, dp[b] * 3, dp[c] * 5, dp[d] * 7),而abcd分别由四个变量维护。

 1 #include<iostream> 2 #include<cstdio> 3 using namespace std; 4 int ans[6000]; 5  6 int getmin(int a, int b, int c, int d) { 7     int e = a < b ? a : b; 8     int f = c < d ? c : d; 9     return e < f ? e : f;10 }11 12 void init() {13     ans[1] = 1;14     int a = 1, b = 1, c = 1, d = 1;15     for(int i = 2; i <= 5842; i++) {16         int res = getmin(ans[a] * 2, ans[b] * 3, ans[c] * 5, ans[d] * 7);17         ans[i] = res;18         if(ans[a] * 2 == res) a++;19         if(ans[b] * 3 == res) b++;20         if(ans[c] * 5 == res) c++;21         if(ans[d] * 7 == res) d++;22     }23     return;24 }25 26 int main() {27     init();    28     // cout << ans[1000] << endl;29     // 45030     int n;31     while(scanf("%d", &n), n) {32         printf("The %d", n);33         if(n % 100 > 10 && n % 100 < 20) {34             printf("th");35             goto loop;36         }37         int res = n % 10;38         if(res == 1) printf("st");39         else if(res == 2) printf("nd");40         else if(res == 3) printf("rd");41         else printf("th");42         loop: printf(" humble number is %d.\n", ans[n]);43     }44     return 0;45 }46 47 /*48 149 250 351 452 1153 1254 1355 2156 2257 2358 10059 100060 584261 062  63 The 1st humble number is 1.64 The 2nd humble number is 2.65 The 3rd humble number is 3.66 The 4th humble number is 4.67 The 11th humble number is 12.68 The 12th humble number is 14.69 The 13th humble number is 15.70 The 21st humble number is 28.71 The 22nd humble number is 30.72 The 23rd humble number is 32.73 The 100th humble number is 450.74 The 1000th humble number is 385875.75 The 5842nd humble number is 2000000000.76 */ 

 

hdu1068【动态规划】