|
| 1 | +/** |
| 2 | + * [313] Super Ugly Number |
| 3 | + * |
| 4 | + * Write a program to find the n^th super ugly number. |
| 5 | + * |
| 6 | + * Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k. |
| 7 | + * |
| 8 | + * Example: |
| 9 | + * |
| 10 | + * |
| 11 | + * Input: n = 12, primes = [2,7,13,19] |
| 12 | + * Output: 32 |
| 13 | + * Explanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first 12 |
| 14 | + * super ugly numbers given primes = [2,7,13,19] of size 4. |
| 15 | + * |
| 16 | + * Note: |
| 17 | + * |
| 18 | + * |
| 19 | + * 1 is a super ugly number for any given primes. |
| 20 | + * The given numbers in primes are in ascending order. |
| 21 | + * 0 < k ≤ 100, 0 < n ≤ 10^6, 0 < primes[i] < 1000. |
| 22 | + * The n^th super ugly number is guaranteed to fit in a 32-bit signed integer. |
| 23 | + * |
| 24 | + * |
| 25 | + */ |
| 26 | +pub struct Solution {} |
| 27 | + |
| 28 | +// submission codes start here |
| 29 | + |
| 30 | +use std::collections::BinaryHeap; |
| 31 | +use std::cmp::Ordering; |
| 32 | +#[derive(Eq, PartialEq)] |
| 33 | +struct Invert { |
| 34 | + base: i32, |
| 35 | + idx: usize, |
| 36 | + value: i32, |
| 37 | +} |
| 38 | + |
| 39 | +impl Ord for Invert { |
| 40 | + fn cmp(&self, other: &Invert) -> Ordering { |
| 41 | + other.value.cmp(&self.value) |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +impl PartialOrd for Invert { |
| 46 | + fn partial_cmp(&self, other: &Invert) -> Option<Ordering> { |
| 47 | + Some(self.cmp(other)) |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +impl Solution { |
| 52 | + pub fn nth_super_ugly_number(n: i32, primes: Vec<i32>) -> i32 { |
| 53 | + let mut vec = vec![1;1]; |
| 54 | + let mut heap: BinaryHeap<Invert> = BinaryHeap::new(); |
| 55 | + for &prime in primes.iter() { |
| 56 | + heap.push(Invert{base: prime, idx: 0, value: prime}); |
| 57 | + } |
| 58 | + for _ in 0..n-1 { |
| 59 | + let mut min = 0; |
| 60 | + if let Some(num) = heap.peek() { |
| 61 | + min = num.value; |
| 62 | + } |
| 63 | + vec.push(min); |
| 64 | + while heap.peek().unwrap().value == min { |
| 65 | + let p = heap.pop().unwrap(); |
| 66 | + heap.push(Invert{base: p.base, idx: p.idx+1, value: p.base * vec[p.idx+1]}); |
| 67 | + } |
| 68 | + } |
| 69 | + *vec.last().unwrap() |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +// submission codes end |
| 74 | + |
| 75 | +#[cfg(test)] |
| 76 | +mod tests { |
| 77 | + use super::*; |
| 78 | + |
| 79 | + #[test] |
| 80 | + fn test_313() { |
| 81 | + assert_eq!(Solution::nth_super_ugly_number(12, vec![2,7,13,19]), 32); |
| 82 | + } |
| 83 | +} |
0 commit comments