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.
题意:
一个数的因子只含有2,3,5,7,则这个数为humble number;
输入n,求第n个humble number 。
思路:DP ,
因为只含有2,3,5,7;所以用2,3,5,7,来生成下面的humble number数,每次取最小的作为下一个humble number数。
刚开始写的,超时了,后来把所有的humble number数先都生成了,然后直接取。
刚开始代码:
#include<iostream>
#include<stdlib.h>
#include<fstream>
#include<string.h>
#include<algorithm>
using namespace std;
int dp[5845];
int min(int b1,int b2,int b3,int b4)
{
int mmin=b1;
if(mmin>b2)
mmin=b2;
if(mmin>b3)
mmin=b3;
if(mmin>b4)
mmin=b4;
return mmin;
}
int DP(int n)
{
memset(dp,0,sizeof(dp));
dp[1]=1;
int b1=1,b2=1,b3=1,b4=1;
for(int i=2;i<=n;i++)
{
dp[i]=min(2*dp[b1],3*dp[b2],5*dp[b3],7*dp[b4]);
if(dp[i]==2*dp[b1])
b1++;
if(dp[i]==3*dp[b2])
b2++;
if(dp[i]==5*dp[b3])
b3++;
if(dp[i]==7*dp[b4])
b4++;
}
return dp[n];
}
int main()
{
//int n;
//DP();
freopen("C:\\Users\\liuzhen\\Desktop\\11.txt","r",stdin);
int n;
while(cin>>n)
{
if(n==0)
break;
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 ";
cout<<DP(n)<<"."<<endl;
}
freopen("con","r",stdin);
system("pause");
return 0;
}
AC代码:
#include<iostream>
#include<stdlib.h>
#include<fstream>
#include<string.h>
#include<algorithm>
using namespace std;
int dp[5845];
int min(int b1,int b2,int b3,int b4)
{
int mmin=b1;
if(mmin>b2)
mmin=b2;
if(mmin>b3)
mmin=b3;
if(mmin>b4)
mmin=b4;
return mmin;
}
int DP()
{
memset(dp,0,sizeof(dp));
dp[1]=1;
int b1=1,b2=1,b3=1,b4=1;
for(int i=2;i<=5842;i++)
{
dp[i]=min(2*dp[b1],3*dp[b2],5*dp[b3],7*dp[b4]);
if(dp[i]==2*dp[b1])
b1++;
if(dp[i]==3*dp[b2])
b2++;
if(dp[i]==5*dp[b3])
b3++;
if(dp[i]==7*dp[b4])
b4++;
}
}
int main()
{
//int n;
DP();
freopen("C:\\Users\\liuzhen\\Desktop\\11.txt","r",stdin);
int n;
while(cin>>n)
{
if(n==0)
break;
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 ";
cout<<dp[n]<<"."<<endl;
}
freopen("con","r",stdin);
system("pause");
return 0;
}