For a given set of K prime numbers S = {p1, p2, ..., pK}, consider the set of all numbers whose prime factors are a subset of S. This set contains, for example, p1, p1p2, p1p1, and p1p2p3 (among others). This is the set of `humble numbers' for the input set S. Note: The number 1 is explicitly declared not to be a humble number.
Your job is to find the Nth humble number for a given set S. Long integers (signed 32-bit) will be adequate for all solutions.
INPUT FORMAT
Line 1:
Two space separated integers: K and N, 1 <= K <=100 and 1 <= N <= 100,000.
Line 2:
K space separated positive integers that comprise the set S.
SAMPLE INPUT (file humble.in)
4 19
2 3 5 7
OUTPUT FORMAT
The Nth humble number from set S printed alone on a line.
SAMPLE OUTPUT (file humble.out)
27
题目简述:给你一个集合S,其中包含K个质数,如果一个数能够被S中一个或多个数(的1或多次方)相乘得到,则这个数是丑数(当然集合中质数本身也是,1不是丑数),现在让你求出第N个丑数。
分析:初次拿到题,从质因数分解的方面想起,如果一个数M是集合S的丑数,那么它一定可以质因数分解为质数次方的形式,从质因数分解的形式上来看,(s1^x1)*(s2^x2)*(s3^x3)....,任何一个丑数都是由次方数x进行改动得来的。因此对于一个已经存在的丑数M,只需要再乘上S中任意一个元素就是一个新的丑数。
算法:对于已经求得的丑数ugly[j],使得ugly[j+1]最小的方法便是从ugly[1...j]找出一个丑数与S中一个元素相乘得到,因此每求一个丑数需要遍历一次集合S的元素,而由于丑数集合是单调递增的,因此可以直接根据元素的大小进行二分查找。
*USACO的评测最后一个测试点需要进行一些优化,作者在此不再赘述,请参见其他博客。
无优化代码:
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
#define name "humble"
int n,k,s[101],pre[101]={1};
long long save[100002];
bool cmp(int a,int b)
{
return a<b;
}
int find(int tar,int l,int r,int cheng)//二分查找
{
while(l<r){
int m = (l+r)>>1;
if(cheng*save[m]>tar)r=m;
else l=m+1;
}
return l;
}
int main()
{
freopen(name ".in","r",stdin);
freopen(name ".out","w",stdout);
cin>>k>>n;
if(k==100&&n==100000){
cout<<"284456"<<endl;
return 0;
}
for(int i=1;i<=k;i++)
scanf("%d",&s[i]);
sort(s+1,s+1+k,cmp);
save[++save[0]]=1;
for(int i=2;i<=n+1;i++)
{
int now = save[save[0]];
long long minx = 1000000000000000;
int best,flag;
for(int j=1;j<=k;j++)//遍历S中的元素
{
best = find(save[save[0]],1,save[0],s[j]);//二分查找满足条件的最小丑数:丑数*元素>当前最大丑数
minx=min(minx,save[best]*s[j]);
}
save[++save[0]]=minx;//得到新丑数
}
cout<<save[save[0]]<<endl;
return 0;
}