您的位置:首页 > 其它

1010 只包含因子2 3 5的数(丑数 二分)

2017-05-10 23:53 211 查看
题意: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。

思路:筛选丑数可以用紫书上的那个优先队列方法,预处理出1e18的丑数,然后二分查找大于等于N的第一个丑数即可。

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<set>
using namespace std;
typedef long long ll;
const int maxn = 1e7+5;
ll a[maxn], cnt;
set<ll> s;

void init()
{
cnt = 0;
priority_queue<ll, vector<ll>, greater<ll> > q;
q.push(2), q.push(3), q.push(5);
while(1)
{
ll tmp = q.top(); q.pop();
a[cnt++] = tmp;
if(tmp > 1e18) break;
if(s.find(tmp*2) == s.end())
q.push(tmp*2), s.insert(tmp*2);
if(s.find(tmp*3) == s.end())
q.push(tmp*3), s.insert(tmp*3);
if(s.find(tmp*5) == s.end())
q.push(tmp*5), s.insert(tmp*5);
}
}

int main(void)
{
init();
int t;
cin >> t;
while(t--)
{
ll n;
scanf("%lld", &n);
int ans = lower_bound(a, a+cnt, n)-a;
printf("%lld\n", a[ans]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: