NCSTOJ 1472 丑数

版权声明:本文为博主原创文章,记录蒟蒻的成长之路,欢迎吐槽~ https://blog.csdn.net/PegasiTIO/article/details/89352665

Description

编写一个程序,找出第 n 个丑数。丑数就是只包含质因数 2, 3, 5 的正整数。注:1是特殊的丑数。示例:输入: n = 10输出: 12解释: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 是前 10 个丑数。

Input

输入一个数n (1 ≤ n ≤ 1500)。

Output

输出第n个丑数。

Sample Input

10

Sample Output

12

题目传送门

单调队列

从小往大扩展,和欸氏筛素数的原理类似,不过这个是反着来,一个数的2,3,5倍数是丑数

为了不漏数,每次都让第i个丑数是2,3,5倍数中最小的那个数,用三个指针,分别指向当前2,3,5倍数用到的最大的数是多少,然后一次扩展

#include <vector>
#include <iostream>
using namespace std;
static const auto io_sync_off = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    return nullptr;
}();

const int maxn = 1505;
int nums[maxn];

int main()
{
    int n;
    cin >> n;

    nums[0] = 1;
    int l2 = 0, l3 = 0, l5 = 0;
    for (int i = 1; i < n; ++i)
    {
        nums[i] = min(nums[l2] * 2, min(nums[l3] * 3, nums[l5] * 5));//取最小的
        if (nums[i] == nums[l2] * 2)
            ++l2;
        if (nums[i] == nums[l3] * 3)
            ++l3;
        if (nums[i] == nums[l5] * 5)
            ++l5;
    }
    cout << nums[n - 1];
    return 0;
}

猜你喜欢

转载自blog.csdn.net/PegasiTIO/article/details/89352665