HDU 1058 Humble Numbers - dp
题目大意:
求质因数只有2, 3, 5, 或7的序列的第k小是多少,序列的第1位是1。
题目分析:
由于只有4中质因数,所以可以dp分别处理。如果开始序列只有
1
,将1分别乘上2,3,5,7,取最小的作为第2个就是1,2
,13和15和17和23再进行比较取出第3个1,2,3
,也就是说由序列中的数,分别乘上2,3,5,7
,在乘的同时进行排序便可以得到整个序列。dp的方法分别巧妙:初始化a = b = c = d = 1 $$dp[i] = min(dp[a] * 2, dp[b] * 3, dp[c] * 5, dp[d] * 7)$$,取了过后相应的a或b或c或d就+1.
code
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<string>
using namespace std;
const int N = 6000;
typedef long long ll;
ll dp[N];
int n;
inline ll myMin(ll a, ll b, ll c, ll d){
ll ret = a;
if(b < ret) ret = b;
if(c < ret) ret = c;
if(d < ret) ret = d;
return ret;
}
inline void init(){
dp[1] = 1;
int a, b, c, d; a = b = c = d = 1;
for(int i = 2; i <= 5900; i++){
dp[i] = myMin(dp[a] * 2, dp[b] * 3, dp[c] * 5, dp[d] * 7);
if(dp[i] == dp[a] * 2) a++;
if(dp[i] == dp[b] * 3) b++;
if(dp[i] == dp[c] * 5) c++;
if(dp[i] == dp[d] * 7) d++;
}
}
int main(){
init();
while(~scanf("%d", &n), n){
printf("The %d", n);
if(n % 10 == 1 && n % 100 != 11) printf("st ");
else if(n % 10 == 2 && n % 100 != 12) printf("nd ");
else if(n % 10 == 3 && n % 100 != 13) printf("rd ");
else printf("th ");
printf("humble number is %I64d.\n", dp[n]);
}
}