【leetcode】313. Super Ugly Number

题目如下:

解题思路:总结一下这么几点,一出一进,优先级队列排序,保证每次输出的都是当前的最小值。解法大致如图:

代码如下:

#include<map>
#include<queue>
using namespace std;
struct node  
{  
    node(int k,int v)
    {
        key = k;
        val = v;
    }
    friend bool operator< (node n1, node n2)  
    {  
        return n1.val > n2.val;
    }  
    int key;  
    int val;  
};  
class Solution {
public:
    int nthSuperUglyNumber(int n, vector<int>& primes) {
        if (n == 1)
            return 1;
        map<int,queue<int>> dic;
        priority_queue<node> qi;

        for(size_t i=0;i<primes.size();i++)
        {
            queue<int> v;
            dic[primes[i]] = v;
            qi.push(node(primes[i],primes[i]));
        }
        int count = 0;
        int res = 0;
        int lastV = 0;

        while (true)
        {
            node v = qi.top();
            qi.pop();

            if (lastV == v.val)
                continue;
            //cout << v.val <<endl;
            lastV = v.val;
            for(size_t i=0;i<primes.size();i++)
            {
                if (v.key <= primes[i])
                    dic[primes[i]].push((v.val * primes[i]));
            }
  
            int nod = dic[v.key].front();
            dic[v.key].pop();
            qi.push(node(v.key,nod));
            count += 1;
            if (count == n - 1)
            {
                res = v.val;
                break;
            }
        }
        return res;            
    }
};

 

posted @ 2018-06-01 10:33  seyjs  阅读(211)  评论(0编辑  收藏  举报