hdu 5878 丑数 STL(pair,priority_queue)

本文介绍了一种使用打表法解决丑数问题的方法,并提供了两种不同的C++实现方案。一种是通过优先队列和集合来生成丑数,另一种则是采用二分查找优化丑数的搜索过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原来把算的数存起来需要时再输出就叫打表,先写个代码找找maxn

http://blog.youkuaiyun.com/qq_22497299/article/details/52565561

51nod1010:https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1010

一段只过部分数据的代码,可能常数有点大:

#include<iostream>
#include<algorithm>
#include<set>
#include<queue>


using namespace std;
typedef long long ll;
const int coeff[3]={2,3,5};
set<ll> s;
const int MAXN = 1e4 + 1e3;


int main(){
    priority_queue<ll, vector<ll>, greater<ll> > pq;
    pq.push(1);
    s.insert(1);
    for(int i=0;i<MAXN;i++){
        ll x=pq.top();
        pq.pop();
        for(int j=0;j<3;j++){
            ll x2=x*coeff[j];
            if(!s.count(x2)){
                s.insert(x2);pq.push(x2);
            }
        }
    }
    int T;
    cin>>T;
    while(T--){
        ll a;
        cin>>a;
        if(a==1){
            cout<<"2"<<endl;
            continue;
        }
        set<ll>::iterator it=s.find(a);
        while(s.find(a)==s.end()){
            a++;
            it=s.find(a);
        }
        cout<<*it<<endl;
    }
    return 0;
}


实际上最好二分:摘自http://blog.youkuaiyun.com/f_zyj/article/details/52077222

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值