题目:http://acm.hdu.edu.cn/showproblem.php?pid=1058
题意:质因子只有2,3,5,7的数字是humble number,求第n个humble number,1<=n<=5842.还有The 5842nd humble number is 2000000000
(一)朴素算法
把humble numbers因式分解为2^i*3^j*5^k*7^L;枚举i, j, k, L,计算小于2000000000的数,因为枚举出来的并不是有序的,所以我们要进行一次排序,排序完成后的就是要求的humble numbers序列
代码如下:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
long long f[31][20][14][12];
long long a[200000];
int main()
{
int n,sum=0;
long long ans;
f[0][0][0][0]=1;
a[sum++] = 1;
for (int i=0;i<=30;i++)
{
for (int j=0;j<=19;j++)
{
for (int k=0;k<=13;k++)
{
for (int l=0;l<=11;l++)
{
if(i-1>=0 && (f[i-1][j][k][l]*2)<=2000000000ll && f[i-1][j][k][l]>0)
{
f[i][j][k][l] = f[i-1][j][k][l] *2;
a[sum++] = f[i][j][k][l];
}
else if(j-1>=0 && (f[i][j-1][k][l]*3)<=2000000000ll && f[i][j-1][k][l]>0)
{
f[i][j][k][l] = f[i][j-1][k][l] * 3;
a[sum++] = f[i][j][k][l];
}
else if(k-1>=0 && (f[i][j][k-1][l]*5)<=2000000000ll && f[i][j][k-1][l]>0)
{
f[i][j][k][l] = f[i][j][k-1][l] * 5;
a[sum++] = f[i][j][k][l];
}
else if(l-1>=0 && (f[i][j][k][l-1]*7)<=2000000000ll && f[i][j][k][l-1]>0)
{
f[i][j][k][l] = f[i][j][k][l-1] *7;
a[sum++] = f[i][j][k][l];
}
}
}
}
}
sort(a,a+sum);
while(scanf("%d",&n)!=EOF)
{
if(n==0) break;
ans = a[n-1];
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 %lld.\n",ans);
}
return 0;
}
(二)DP算法
f[i]表示第i个humble numbers,那么它一定是等于之前的某一个humble numbers f[j]*2 或 f[j]*3 或 f[j]*5 或f[j]*7;
那么我们可以由前面的humble numbers 递推出后面的humble numbers
f[i] = min {f[p1]*2,f[p2]*3,f[p3]*5,f[p4]*7}
用的上一段代码改的,所以数组用的a,且是从0到5841的;
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
long long a[200000];
int main()
{
int n,p1,p2,p3,p4;
long long ans;
a[0] = 1;
p1 = p2 = p3 = p4 = 0;
for(int i=1;i<5842;i++)
{
a[i] = min (min (min (a[p1]*2, a[p2]*3), a[p3]*5), a[p4]*7);
if (a[i] == a[p1]*2) p1++;
if (a[i] == a[p2]*3) p2++;
if (a[i] == a[p3]*5) p3++;
if (a[i] == a[p4]*7) p4++;
}
while(scanf("%d",&n)!=EOF)
{
if(n==0) break;
ans = a[n-1];
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 %lld.\n",ans);
}
return 0;
}
由于数据很小,一共才5842个数所以朴素算法跟DP时间上差别不大,但内存占用大一些;