题目
Write a program to find the nth super ugly number.
Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k. For example, [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32] is the sequence of the first 12 super ugly numbers given primes = [2, 7, 13, 19] of size 4.
Note:
(1) 1 is a super ugly number for any given primes.
(2) The given numbers in primes are in ascending order.
(3) 0 < k ≤ 100, 0 < n ≤ 106, 0 < primes[i] < 1000.
题目翻译
超级素数,素因子只包含规定素因子序列的元素。然后求第n个超级素数。
注意:
1,1是超级素数
2,给的素因子序列为升序
分析
该题可以任务是丑数的一个变种。只是素因子变为了一个素数序列。本质没有变。所以思路请出门右转,看
264. Ugly Number II-思路详解 http://blog.csdn.net/SJWL2012/article/details/53192810
代码
class Solution {
public:
int nthSuperUglyNumber(int n, vector<int>& primes) {
int primes_size = primes.size();
int *pUglyNumber = new int[n];
pUglyNumber[0] = 1;
int nextUglyIndex = 1;
vector<int*> pMultiN(primes_size,pUglyNumber); //初始化
while(nextUglyIndex < n){
int min = FindMin(pMultiN,primes);
pUglyNumber[nextUglyIndex] = min;
for(int i = 0; i < primes_size; i ++){
while(*(pMultiN[i])*primes[i] <= pUglyNumber[nextUglyIndex]){
++pMultiN[i];
}
}
++nextUglyIndex;
}
int ugly = pUglyNumber[n-1];
delete[] pUglyNumber;
return ugly;
}
int FindMin(vector<int*> &pMultiN,vector<int> &primes){
int primes_size = primes.size();
int min = *(pMultiN[0])*primes[0];
for(int i = 1; i < primes_size; ++i){
if(*(pMultiN[i])* primes[i] < min){
min = *(pMultiN[i])* primes[i];
}
}
return min;
}
};