题目概述
1和因子只有2,3,5,7的数称为丑数,给出序号N,求对应该序号的丑数
时限
1000ms/2000ms
输入
每行一个正整数N,输入到N=0结束
限制
1<=N<=5842
输出
每行一个字符串
The # humble number is @.
其中#为N和N在英文中对应的序数后缀,@为所求丑数
样例输入
1
2
3
4
11
12
13
21
22
23
100
1000
5842
0
样例输出
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.
讨论
dp,有点出乎意料,本来以为又是公式什么的,确实,既然因子只有那四个,无非就是那四个乘数的数量不一样罢了,状态转移方程f(n)=min(f(n-1)*a,f(n-1)*b,f(n-1)*c,f(n-1)*d),其中a,b,c,d分别代表因子2,3,5,7的数量,每次四个数中被选中的数所含字母+1,比如选中15,3和5都是其因子,则b,c各+1,预处理一次,对后面每次询问直接返回结果即可
题解状态
124MS,1740K,1505 B,C++
题解代码
#include<algorithm>
#include<string.h>
#include<stdio.h>
#include<vector>
using namespace std;
#define INF 0x3f3f3f3f
#define maxx(a,b) ((a)>(b)?(a):(b))
#define minn(a,b) ((a)<(b)?(a):(b))
#define MAXN 5842
#define memset0(a) memset(a,0,sizeof(a))
int N;
int nums[MAXN];//存放丑数的数组
bool f;//控制预处理
void fun()
{
if (!f) {//
nums[0] = 1;//1的因子只有自己 特殊处理
int a, b, c, d;
a = b = c = d = 0;
for (int p = 1; p < 5842; p++) {
nums[p] = min({ nums[a] * 2, nums[b] * 3, nums[c] * 5, nums[d] * 7 });
if (nums[p] == nums[a] * 2)
a++;
if (nums[p] == nums[b] * 3)
b++;
if (nums[p] == nums[c] * 5)
c++;
if (nums[p] == nums[d] * 7)
d++;
}
}
switch (N % 100) {//下面两个switch只是为了处理输出格式
case 11:
printf("The %dth humble number is %d.\n", N, nums[N - 1]);//output
break;
case 12:
printf("The %dth humble number is %d.\n", N, nums[N - 1]);//output
break;
case 13:
printf("The %dth humble number is %d.\n", N, nums[N - 1]);//output
break;
default:
switch (N % 10) {
case 1:
printf("The %dst humble number is %d.\n", N, nums[N - 1]);//output
break;
case 2:
printf("The %dnd humble number is %d.\n", N, nums[N - 1]);//output
break;
case 3:
printf("The %drd humble number is %d.\n", N, nums[N - 1]);//output
break;
default:
printf("The %dth humble number is %d.\n", N, nums[N - 1]);//output
}
}
}
int main(void)
{
//freopen("vs_cin.txt", "r", stdin);
//freopen("vs_cout.txt", "w", stdout);
while (~scanf("%d", &N) && N) {//input
fun();
f = 1;//预处理一次之后就再不处理了
}
}