HDU 1058 Humble Numbers

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   art   

既然將這道題分類到動態規劃的題目裡面,一開始便是用動態規劃的思想去思考。

一個上午毫無突破,看的人家的題解。

定義四個偽指標存放下標,分別表示的意思是在已知的醜數中,能夠與2,3,5,7相乘的最小的數的下標。

上面這句話要好好體會。

也就是說dp[p1] * 2 能夠得到一個新的醜數,其他三個以此類推。

但我們要求的是已知最大丑數中緊挨著的下一個醜數,那就是能夠產生新醜數的最小值了。

即min(dp[p1] * 2, dp[p2] * 3, dp[p3] * 5, dp[p4] * 7);

 

另外需要注意的一點是,在DP()中會遇到某兩個產生的醜數同為最小值的情況,那麼對應的“指標”也要同時自增1。

比如i = 5的時候,p1 = 3, p2 = 2,此時dp[p1] * 2 == dp[p2] * 3 == 6;

如果只執行++p1不執行++p2的話,那麼會漏掉9這個醜數。

 

最後吐槽一下蛋疼的輸出。。

╮(╯▽╰)╭,何時才能不看題解,通過自己思考把dp題目A出來呢。。

 

 1 //#define LOCAL 2 #include <iostream> 3 #include <cstdio> 4 #include <cstring> 5 #include <algorithm> 6 using namespace std; 7  8 int dp[5850]; 9 10 inline int min(int a, int b, int c, int d)11 {12     a = min(a, b);13     c = min(c, d);14     return min(a, c);15 }16 17 void DP(void)18 {19     int i;20     int p1 = 1, p2 = 1, p3 = 1, p4 = 1;21     dp[1] = 1;22     for(i = 2; i <= 5842; ++i)23     {24         dp[i] = min(dp[p1] * 2, dp[p2] * 3, dp[p3] * 5, dp[p4] * 7);25         if(dp[i] == dp[p1] * 2)26             ++p1;27         if(dp[i] == dp[p2] * 3)28             ++p2;29         if(dp[i] == dp[p3] * 5)30             ++p3;31         if(dp[i] == dp[p4] * 7)32             ++p4;33     }34 } 35 36 int main(void)37 {38     #ifdef LOCAL39         freopen("1058in.txt", "r", stdin);40     #endif41 42     DP();43     int n;44     while(scanf("%d", &n) && n)45     {46         if(n % 10 == 1 && n % 100 != 11)47             printf("The %dst humble number is ", n);48         else if (n % 10 == 2 && n % 100 != 12)49         {50             printf("The %dnd humble number is ", n);51         }52         else if (n % 10 == 3 && n % 100 != 13)53         {54             printf("The %drd humble number is ", n);55         }56         else57             printf("The %dth humble number is ", n);58 59         printf("%d.\n", dp[n]);60     }61     return 0;62 }
代碼君

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.