zoj 1095 Humble Numbers

zoj 1095 Humble Numbers

/*
此题有一种常规解法
就是设一个长度为 5842 的数组
往里面存数
由于已知数组中存放的最大数为2000000000
而且数组中元素都是由其中元素与2 3 5 7的积组成的
所以只需循环5842次将小于等于上界且不与已产生的元素相等的元素填入表中即可
然后在对数组中元素进行排序
最后输出hum[n-1]即可
下面是另一种更为巧妙且效率更高的解法 
*/
#define LOCAL
#include<iostream>
using namespace std;
#define N 5842
int main()
{
#ifdef LOCAL
       freopen("input.txt","r",stdin);
       freopen("output.txt","w",stdout);
#endif
    int t1,t2,m[4]={0,0,0,0},i,n,hum[N]={1};
    for(i=1;i<N;i++)
    {
           t1=(2*hum[m[0]]>3*hum[m[1]]?3*hum[m[1]]:2*hum[m[0]]);              
           t2=(5*hum[m[2]]>7*hum[m[3]]?7*hum[m[3]]:5*hum[m[2]]);
           hum[i]=(t1>t2?t2:t1); 
           if(hum[i]==2*hum[m[0]]) m[0]++;      //这里不能写成else if() 
           if(hum[i]==3*hum[m[1]]) m[1]++;      //去重的关键步骤! 
           if(hum[i]==5*hum[m[2]]) m[2]++;
           if(hum[i]==7*hum[m[3]]) m[3]++;
    } 
    while(cin>>n&&n)
    {
            cout<<"The "<<n;
            if(n%100==11||n%100==12||n%100==13||n%100==14) cout<<"th humble number is "; //注意这里! 
            else switch(n%10)
            {
                case 1:cout<<"st humble number is ";break;
                case 2:cout<<"nd humble number is ";break;
                case 3:cout<<"rd humble number is ";break;
                default:cout<<"th humble number is ";break;            
            }                
            cout<<hum[n-1];
            cout<<"."<<endl;
    }
    return 0;
}

发表回复