51Nod-1010-只包含2 3 5的数

235 篇文章 1 订阅
228 篇文章 1 订阅

ACM模版

描述

描述

题解

先打表生成丑数,然后二分查找到大于等于n的第一个数。

代码

#include <iostream>
#include <cstdio>
#include <queue>

using namespace std;

typedef unsigned long long ull;

const int MAXN = 1e4 + 1e3;

/*
 * Ugly Numbers
 * Ugly numbers are numbers whose only prime factors are 2, 3 or 5.
 * 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, ...
 */
typedef pair<ull, int> node_type;

ull result[MAXN];

void init()
{
    priority_queue<node_type, vector<node_type>, greater<node_type>> Q;
    Q.push(make_pair(1, 2));
    for (int i = 0; i < MAXN; i++)
    {
        node_type node = Q.top();
        Q.pop();
        switch (node.second)
        {
            case 2:
                Q.push(make_pair(node.first * 2, 2));
            case 3:
                Q.push(make_pair(node.first * 3, 3));
            case 5:
                Q.push(make_pair(node.first * 5, 5));
        }
        result[i] = node.first;
    }

    return ;
}

/*
 *  传入参数必须l <= h
 *  假设a数组已经按从小到大排序
 *  返回值l总是合理的
 */
int bs(ull a[], int l, int h, ull v)
{
    int m;
    while (l < h)
    {
        m = (l + h) >> 1;
        if (a[m] < v)
        {
            l = m + 1;
        }
        else
        {
            h = m;
        }
    }
    return l;
}

int main(int argc, const char * argv[])
{
    freopen("input.txt", "r", stdin);
//    freopen("input.txt", "w", stdin);

    init();

    int T;
    cin >> T;

    ull n;
    while (T--)
    {
        cin >> n;

        int key = bs(result, 1, MAXN - 1, n);

        cout << result[key] << '\n';
    }
    return 0;
}

参考

STL简介
二分查找

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值