-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode-313.c
More file actions
85 lines (75 loc) · 1.82 KB
/
LeetCode-313.c
File metadata and controls
85 lines (75 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*************************************************************************
} > File Name: LeetCode-313.c
> Author: ltw
> Mail: 3245849061@qq.com
> Created Time: Thu 21 May 2020 10:53:36 PM CST
************************************************************************/
#define swap(a, b) { \
__typeof(a) __temp = a; \
a = b, b = __temp; \
}
typedef struct Heap {
long long *data;
int n, size;
} Heap;
Heap *init(int n) {
Heap *h = (Heap *)malloc(sizeof(Heap));
h->n = 0;
h->size = n + 1;
h->data = (long long *)malloc(sizeof(long long) * h->size);
return h;
}
int empty(Heap *h) {
return h->n == 0;
}
#define V(x) h->data[x]
void push(Heap *h, long long val) {
V(++(h->n)) = val;
int ind = h->n;
while (ind > 1 && V(ind) < V(ind >> 1)) {
swap(V(ind), V(ind >> 1));
ind >>= 1;
}
return ;
}
long long top(Heap *h) { return V(1); }
void pop(Heap *h) {
if (empty(h)) return ;
V(1) = V((h->n)--);
int ind = 1;
while ((ind << 1) <= h->n) {
int temp = ind, l = ind << 1, r = ind << 1 | 1;
if (V(l) < V(temp)) temp = l;
if (r <= h->n && V(r) < V(temp)) temp = r;
if (temp == ind) break;
swap(V(temp), V(ind));
ind = temp;
}
return ;
}
void clear(Heap *h) {
if (h == NULL) return ;
free(h->data);
free(h);
return ;
}
int nthSuperUglyNumber(int n, int* primes, int primesSize){
int k = primesSize;
Heap *h = init(n * primesSize);
push(h, 1);
long long ans = 0;
while (n--) {
ans = top(h);
pop(h);
int i = k - 1;
for (; i > 0; i--) {
if (ans % primes[i]) continue;
break;
}
for (int j = i; j < k; j++) {
push(h, ans * primes[j]);
}
}
clear(h);
return ans;
}