您的位置:首页 > 其它

HDU 1058 Humble Numbers 【DP】

2016-08-09 14:21 363 查看
题目链接

题意

定义“Humble Numbers”是素因子只含有2,3,5,7的数,求第n个Humble Number是多少。

分析

显然直接求出某个范围以内所有的humble Numbers,关键是如何枚举才能保证枚举出来的数是递增的。

这里用DP来实现,记录当前没有乘以某个因子中的最大数再乘以这个因子得到的数中的最小值,这样说很抽象,看代码:

while(m<=5842)
{
int temp=minn(2*a[b2],3*a[b3],5*a[b5],7*a[b7]);
a[++m]=temp;
if(temp==2*a[b2])
b2++;
if(temp==3*a[b3])
b3++;
if(temp==5*a[b5])
b5++;
if(temp==7*a[b7])
b7++;
}


b2,b3,b5,b7最开始都等于1

这样能够保证每次乘上某个因子过后一定是未求的Humble Numbers中的最小数

AC代码

//HDU 1058 Humble Numbers
//AC 2016-8-8 16:08:11
//DP
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cctype>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <set>
#include <string>
#include <map>
#include <queue>
#include <deque>
#include <list>
#include <sstream>
#include <stack>
using namespace std;

#define cls(x) memset(x,0,sizeof x)
#define inf(x) memset(x,0x3f,sizeof x)
#define neg(x) memset(x,-1,sizeof x)
#define ninf(x) memset(x,0xc0,sizeof x)
#define st0(x) memset(x,false,sizeof x)
#define st1(x) memset(x,true,sizeof x)
#define INF 0x3f3f3f3f
#define lowbit(x) x&(-x)
#define bug cout<<"here"<<endl;
//#define debug

long long a[6000];

int minn(int a,int b,int c,int d)
{
return min(min(a,b),min(c,d));
}

int main()
{
#ifdef debug
freopen("E:\\Documents\\code\\input.txt","r",stdin);
freopen("E:\\Documents\\code\\output.txt","w",stdout);
#endif
long long temp;
a[1]=1;
int n,b2,b3,b5,b7;
b2=b3=b5=b7=1;
int m=1;
while(m<=5842)
{
int temp=minn(2*a[b2],3*a[b3],5*a[b5],7*a[b7]);
a[++m]=temp;
if(temp==2*a[b2])
b2++;
if(temp==3*a[b3])
b3++;
if(temp==5*a[b5])
b5++;
if(temp==7*a[b7])
b7++;
}
while(cin>>n&&n)
{
cout<<"The "<<n;
if(n%10==1&&n%100!=11)
cout<<"st";
else if(n%10==2&&n%100!=12)
cout<<"nd";
else if(n%10==3&&n%100!=13)
cout<<"rd";
else
cout<<"th";
cout<<" humble number is "<<a
<<"."<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dp HDU