Humble Numbers
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Problem Description
A number whose only prime factors are 2,3,5 or 7 is called a humble number. The sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 25, 27, ... shows the first 20 humble numbers.
Write a program to find and print the nth element in this sequence
Write a program to find and print the nth element in this sequence
Input
The input consists of one or more test cases. Each test case consists of one integer n with 1 <= n <= 5842. Input is terminated by a value of zero (0) for n.
Output
For each test case, print one line saying "The nth humble number is number.". Depending on the value of n, the correct suffix "st", "nd", "rd", or "th" for the ordinal number nth has to be used like it is shown in the sample output.
Sample Input
1 2 3 4 11 12 13 21 22 23 100 1000 5842 0
Sample Output
The 1st humble number is 1. The 2nd humble number is 2. The 3rd humble number is 3. The 4th humble number is 4. The 11th humble number is 12. The 12th humble number is 14. The 13th humble number is 15. The 21st humble number is 28. The 22nd humble number is 30. The 23rd humble number is 32. The 100th humble number is 450. The 1000th humble number is 385875. The 5842nd humble number is 2000000000.
————————————————————暴走的分割线————————————————————
前言:啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊不会做 看题解 --_--
思路:考虑这样一个数组:
{0 1 2 3 (4) 5 (6) 7 ...}
它是由它所含元素的2倍、3倍、5倍、7倍构成的。(初始元素是1)
转移条件有4个:2倍转移、3倍转移、5倍转移和7倍转移。暂且称之为4个转移因子。
2、3、5、7都是分别由1通过4个转移因子转移过来的。那么中间的4、6是怎么得到的呢?
(暂时忽略7倍转移)
也就是说6是由2、3同时转移过来的。
在这个数组当中一个接一个的填写数字。每个数字应该是备选数字(比如填到第6个数字6的时候,备选数字是2的3倍、3的2倍、5的2倍、1的7倍
)当中最小的那个。如果备选数字有相等的情况,那么就是同时转移过来的。
状态转移方程:dp[i] = min{2*dp[a], 3*dp[b], 5*dp[c], 7*dp[d]}
P.S. 我就不吐槽这题考英语了
代码如下:
/*
ID: j.sure.1
PROG:
LANG: C++
*/
/****************************************/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <ctime>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <climits>
#include <iostream>
#define LL long long
using namespace std;
const int INF = 0x3f3f3f3f;
/****************************************/
const int N = 6000;
int i2, i3, i5, i7;
LL dp[N] = {0, 1};
void solve()
{
i2 = i3 = i5 = i7 = 1;
for(int i = 2; i <= 5842; i++) {
dp[i] = min(min(2*dp[i2], 3*dp[i3]), min(5*dp[i5], 7*dp[i7]));
if(dp[i] == 2*dp[i2]) i2++;
if(dp[i] == 3*dp[i3]) i3++;
if(dp[i] == 5*dp[i5]) i5++;
if(dp[i] == 7*dp[i7]) i7++;
}
}
int main()
{
#ifdef J_Sure
// freopen("000.in", "r", stdin);
// freopen(".out", "w", stdout);
#endif
int x;
solve();
char s[5];
while(scanf("%d", &x), x) {
if(x % 100 >= 10 && x % 100 <= 20) {
strcpy(s, "th");
}
else {
switch(x % 10)
{
case 1: strcpy(s, "st"); break;
case 2: strcpy(s, "nd"); break;
case 3: strcpy(s, "rd"); break;
default:strcpy(s, "th"); break;
}
}
printf("The %d%s humble number is %I64d.\n", x, s, dp[x]);
}
return 0;
}