您的位置:首页 > 产品设计 > UI/UE

hdu 5878 丑数 STL(pair,priority_queue)

2017-09-08 23:20 423 查看
原来把算的数存起来需要时再输出就叫打表,先写个代码找找maxn
http://blog.csdn.net/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.csdn.net/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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: