【51nod-1010】因子只含有2 3 5的数

K的因子中只包含2 3 5。满足条件的前10个数是:2,3,4,5,6,8,9,10,12,15。
所有这样的K组成了一个序列S,现在给出一个数n,求S中 >= 给定数的最小的数。
例如:n = 13,S中 >= 13的最小的数是15,所以输出15。
 

Input

第1行:一个数T,表示后面用作输入测试的数的数量。(1 <= T <= 10000)
第2 - T + 1行:每行1个数N(1 <= N <= 10^18)

Output

共T行,每行1个数,输出>= n的最小的只包含因子2 3 5的数
 
代码1:3个for
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
map<LL, bool>M;
LL a[300000];
int main()
{
    int t, l = 0;
    LL s = 1;
    for(LL i = 1; i <= 1e18; i = i*2)
        for(LL j = 1; j*i <= 1e18; j = j*3)
            for(LL k = 1; i*j*k <= 1e18; k = k*5)
            {
                if(!M[i*j*k] && i*j*k != 1)
                {
                    M[i*j*k] = 1;
                    a[l++] = i*j*k;
                }
            }
    sort(a, a+l);
    cin>>t;
    LL n;
    while(t--)
    {
        scanf("%lld", &n);
        int pos = lower_bound(a, a+l, n) - a;
        printf("%lld
", a[pos]);
    }
    return 0;
}

代码2:bfs

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N=10010;

LL a[N] , b[N*2];
queue<LL> q;
map<LL , bool> m;
int main()
{
    LL n = 1e18;
    q.push(1);
    m[1]= 1;

    int k = 0;
    while (!q.empty())
    {
        LL x = q.front();
        a[k ++] = x;
        q.pop();
        if (x*2<=n && !m[x*2])  q.push(x*2) , m[x*2] = 1;
        if (x*3<=n && !m[x*3])  q.push(x*3) , m[x*3] = 1;
        if (x*5<=n && !m[x*5])  q.push(x*5) , m[x*5] = 1;
    }
    sort(a, a+k);
    int cas;
    scanf("%d", &cas);
    while (cas -- )
    {
        LL y;
        scanf("%lld", &y);
        int id = lower_bound(a, a+k, y) - a;
        printf("%lld
", a[id]);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/lesroad/p/9502462.html