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;
- }
- struct Queue 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].k > base.heap[l].k) i = l;
- if (r < n && base.heap[i].k > base.heap[r].k) i = r;
- if (i == j) break;
- base = swap(base, i, j);
- }
- return base;
- }
- 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].k > q.heap[i].k) {
- 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 n, m, i, ans = 0, cur = 0, cluster = 0;
- struct Help x;
- scanf("%d\n", &n);
- scanf("%d\n", &m);
- int *data = (int*)malloc(2 * m * sizeof(int));
- for (i = 0; i < m; i++) {
- if (i != m - 1) {
- scanf("%d ", &data[2 * i]);
- scanf("%d\n", &data[2 * i + 1]);
- }
- else {
- scanf("%d ", &data[2 * i]);
- scanf("%d", &data[2 * i + 1]);
- }
- }
- struct Queue q = InitQueue(m);
- while (cur < 2 * m) {
- if (q.count > 0 && q.heap[0].k <= ans) {
- cluster--;
- q.count--;
- if (q.count > 0) {
- q.heap[0] = q.heap[q.count];
- q = heapify(0, q.count, q);
- }
- }
- if (data[cur] <= ans) {
- if (cluster < n) {
- cluster++;
- x.k = x.v = ans + data[cur + 1];
- q = Insert(q, x);
- cur += 2;
- }
- }
- ans++;
- }
- if (q.count > 0) ans = q.heap[q.count - 1].v;
- printf("%d\n", ans);
- free(data);
- free(q.heap);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement