Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- struct Help {
- int v, k;
- };
- struct Queue {
- struct Help *heap;
- int cap, count;
- };
- struct Queue swap(struct Queue base, int a, int b)
- {
- int v = base.heap[a].v, k = base.heap[a].k;
- base.heap[a] = base.heap[b];
- base.heap[b].v = v;
- base.heap[b].k = k;
- return base;
- }
- void heapify(int i, int n, struct Queue base)
- {
- for (;;) {
- int l = 2 * i + 1;
- int r = l + 1;
- int j = i;
- if (l < n && base.heap[i].v < base.heap[j].v) i = l;
- if (r < n && base.heap[i].v < base.heap[r].v) i = r;
- if (i == j) break;
- swap(base, i, j);
- }
- }
- struct Queue InitQueue(int n)
- {
- struct Queue q;
- struct Help *d = (struct Help*)malloc(n * sizeof(struct Help));
- q.heap = d;
- q.cap = n;
- q.count = 0;
- return q;
- }
- int QueueEmpty(struct Queue q)
- {
- return (q.count == 0);
- }
- struct Queue Insert(struct Queue q, struct Help x)
- {
- int i = q.count;
- if (i == q.cap) printf("FULL");
- q.count = i + 1;
- q.heap[i] = x;
- while (i > 0 && q.heap[(i - 1) / 2].v > q.heap[i].v) {
- q = swap(q, (i - 1) / 2, i);
- i = (i - 1) / 2;
- }
- return q;
- }
- struct Help ExtractMin(struct Queue q)
- {
- if (q.count == 0) printf("NULL");
- return q.heap[0];
- }
- int main()
- {
- int j, i, k, n = 0, cur = 0, now;
- struct Help x;
- scanf("%d\n", &k);
- int count[k];
- for (i = 0; i < k; i++) {
- scanf("%d", &count[i]);
- n += count[i];
- }
- scanf("\n");
- int all[n];
- for (i = 0; i < k; i++) {
- for (j = 0; j < count[i]; j++) scanf("%d", &all[cur + j]);
- cur += count[i];
- if (i != k - 1) scanf("\n");
- }
- struct Queue q = InitQueue(k);
- cur = 0;
- for (i = 0; i < k; i++) {
- x.v = all[cur];
- x.k = i;
- q = Insert(q, x);
- cur += count[i];
- }
- int index[k];
- for (i = 0; i < k; i++) index[i] = 1;
- n -= k;
- while (n > 0) {
- x = ExtractMin(q);
- q.count--;
- if (q.count > 0) {
- q.heap[0] = q.heap[q.count];
- heapify(0, q.count, q);
- }
- cur = x.k;
- printf("%d ", x.v);
- if (index[cur] < count[cur]) {
- now = 0;
- for (i = 0; i < cur; i++) now += count[i];
- now += index[cur];
- x.v = all[now];
- index[cur]++;
- q = Insert(q, x);
- n--;
- }
- }
- for (i = 0; i < q.count; i++) printf("%d ", q.heap[i].v);
- printf("\n");
- free(q.heap);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement