POJ 1338 Ugly Numbers

http://poj.org/problem?id=1338b

最小的丑数是1,以后的丑数为在以前的基础上进行*2, *3, *5....

那么设第i个丑数为F[i]=min{F[n2]*2, F[n3]*3, F[n5]*5},其中n2, n3, n5....表示进行衍生丑数的下标。暴力的打出1500个丑数要很久很久....才出来结果....

代码如下:

View Code
/*  POJ 1338丑数

*/

#include<stdio.h>

#include<iostream>

using namespace std;

long long f[1505];

long long minx(long long x1, long long x2, long long x3)

{

     long long xx=999999999;

     if(x1<xx)  xx=x1;

     if(x2<xx)  xx=x2;

     if(x3<xx)  xx=x3;

     return xx;

}

int main()

{

    int i, n2=1, n3=1, n5=1, n;

    f[1]=1;

    for(i=2; i<=1500; i++)

    {

        f[i]=minx(f[n2]*2, f[n3]*3, f[n5]*5);

        if(f[i]==f[n2]*2)  n2++;

        if(f[i]==f[n3]*3)  n3++;

        if(f[i]==f[n5]*5)  n5++;

    }

    while(cin>>n)

    {

        if(n==0)  break;

        cout<<f[n]<<endl;

    }

    return 0;

} 
原文地址:https://www.cnblogs.com/Hilda/p/2939691.html