题目链接: http://poj.org/problem?id=1338

题意 :只有素数因子 2, 3, 5 的数字才成为丑陋数字,现给出一个数字 N , 求在丑陋数字的序列里, 第N个丑陋数字是多少。

 

一开始想的简单粗暴, 搞个循环去存储丑陋数字了。。到最后发现输入N=1500的时候, 压根什么都出不来, 已哭死。。

比赛结束后百度了一下, 才发现自己真的是单细胞生物, 找不到这个规律。。。

*********

规律如下:

       这个丑陋数字集合是通过集合里的每一个数 × 2,× 3,× 5来扩展的,要想从小到大,从num[1]开始扩展时,由于× 2,× 3,× 5大小不同,所以num[]的下一个元素是这三个数的最小值。所以到下次时,2是再乘以新的元素,而3,5还在乘原来的元素,但这三个数比较后最小的继续添加进集合里。由于有了这样的延迟作用,我们可以设置三个指针p2,p3,p5分别指向2,3,5待乘的数。

 

/////要记得处理重复的数,在每扩展一个元素时,判断该数是否能通过其他数来乘得,是的话就右移p。

代码:

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
#include <stack>
#include<vector>
#include <cstring>
using namespace std;
#define INF 0xfffffff
#define maxn 1550
long long a[maxn];
int main()
{
    int  n, n2, n3, n5;
     n2=n3=n5=1;
    a[1]=1;
    for(int i=2; i<=1500; i++)
    {
        a[i]=min(a[n2]*2, min(a[n3]*3, a[n5]*5));

        if(a[i] == a[n2]*2) n2++;
        if(a[i] == a[n3]*3) n3++;
        if(a[i] == a[n5]*5) n5++;
    }

    while(scanf("%d",&n),n)
    {
        printf("%lld\n",a[n]);
    }
    return 0;
}
View Code

 

 

 

 

除此之外,还询问了同学他是怎么做的,发现虽然也暴力,但还是有思路可解的,比自己强的不止一点点。。。

 

2, 3,5乘得的数全打表

然后排序去重就成了

 

#include <stdio.h>
#include <algorithm>
#include <math.h>
using namespace std;
double x[300000];
double Pow(int a, int b)
{
    double ans = 1;
    for(int i=1; i<=b; i++)
        ans*=a;
    return ans;
}
int main()
{
    int cnt = 0;
    for(int i=0; i<=30; i++)
        for(int j=0; j<=30; j++)
         for(int k=0; k<=30; k++)
         x[cnt++] = Pow(2, i)*Pow(3, j)*Pow(5, k);
         sort(x, x+cnt);
         int top = unique(x, x+cnt)-x;
    int n;
    while(scanf("%d", &n), n)
        printf("%.0f\n", x[n-1]);
    return 0;
}
View Code

 

posted on 2016-07-15 21:52  不忧尘世不忧心  阅读(228)  评论(0编辑  收藏  举报