2016SDAU课程练习三1004

题目大意:

由2,3,5,7组成的数给定5842个,输入n,求第n个数。

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.
第i个数一定是前i-1个数中任何一个*2/3/5/7得到的。用dp做出第一种,但是网上给了第二种方法,而且复杂度更小,是O(n):递推。

①:dp

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
    int  a[4]={2,3,5,7};
    long long dp[5842];
    dp[1]=1;//必不可少
    for(int i=2;i<=5842;i++)
    {
        dp[i]=0x7fffffff;//int范围内的最大值
        for(int j=0;j<4;j++)
        {


        for(int k=i-1;k>=1;k--)
        {
            if(dp[k]*a[j]<=dp[i-1])
                break;
            if(dp[k]*a[j]<dp[i])
                dp[i]=dp[k]*a[j];
        }
        }
    }
    int n;
    while(cin>>n&&n!=0)
    {
        if(n%10==1&&n%100!=11)//注意:11,12,13,都是th的
        {
            cout<<"The "<<n<<"st humble number is "<<dp[n]<<"."<<endl;
        }
        else if(n%10==2&&n%100!=12)
        {
            cout<<"The "<<n<<"nd humble number is "<<dp[n]<<"."<<endl;
        }
        else if(n%10==3&&n%100!=13)
            {
            cout<<"The "<<n<<"rd humble number is "<<dp[n]<<"."<<endl;
        }
        else{
            cout<<"The "<<n<<"th humble number is "<<dp[n]<<"."<<endl;
        }
    }
    return 0;
}

②:递推

#include <iostream>//用递推的方法
#include <cstring>
using namespace std;
int min(int a,int b){
   if(a<b) return a;
   else return b;
}
int main(){
   long D[5843];
   memset(D,0,sizeof(D));
   D[1]=1;
   int i,i1=1,i2=1,i3=1,i4=1;
   int t1,t2,t3,t4;
   for(i=2;i<5843;i++){
      t1=D[i1]*2;
      t2=D[i2]*3;
      t3=D[i3]*5;
      t4=D[i4]*7;
      D[i]=min(min(t1,t2),min(t3,t4));
      if(D[i]==t1) i1++;
      if(D[i]==t2) i2++;
      if(D[i]==t3) i3++;
      if(D[i]==t4) i4++;
   }
      int n;
    while(cin>>n&&n!=0)
    {
        if(n%10==1&&n%100!=11)
        {
            cout<<"The "<<n<<"st humble number is "<<D[n]<<"."<<endl;
        }
        else if(n%10==2&&n%100!=12)
        {
            cout<<"The "<<n<<"nd humble number is "<<D[n]<<"."<<endl;
        }
        else if(n%10==3&&n%100!=13)
            {
            cout<<"The "<<n<<"rd humble number is "<<D[n]<<"."<<endl;
        }
        else{
            cout<<"The "<<n<<"th humble number is "<<D[n]<<"."<<endl;
        }
    }
    return 0;
}

阅读更多
个人分类: 动态规划
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭