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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值