Advertisement
Void-voiD

Untitled

Dec 19th, 2018
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.49 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. struct Help {
  5. int v, k;
  6. };
  7.  
  8. struct Queue {
  9. struct Help *heap;
  10. int cap, count;
  11. };
  12.  
  13. struct Queue swap(struct Queue base, int a, int b)
  14. {
  15. int v = base.heap[a].v, k = base.heap[a].k;
  16. base.heap[a] = base.heap[b];
  17. base.heap[b].v = v;
  18. base.heap[b].k = k;
  19. return base;
  20. }
  21.  
  22. struct Queue heapify(int i, int n, struct Queue base)
  23. {
  24. for (;;) {
  25. int l = 2 * i + 1;
  26. int r = l + 1;
  27. int j = i;
  28. if (l < n && base.heap[i].k > base.heap[l].k) i = l;
  29. if (r < n && base.heap[i].k > base.heap[r].k) i = r;
  30. if (i == j) break;
  31. base = swap(base, i, j);
  32. }
  33. return base;
  34. }
  35.  
  36. struct Queue InitQueue(int n)
  37. {
  38. struct Queue q;
  39. struct Help *d = (struct Help*)malloc(n * sizeof(struct Help));
  40. q.heap = d;
  41. q.cap = n;
  42. q.count = 0;
  43. return q;
  44. }
  45.  
  46. int QueueEmpty(struct Queue q)
  47. {
  48. return (q.count == 0);
  49. }
  50.  
  51. struct Queue Insert(struct Queue q, struct Help x)
  52. {
  53. int i = q.count;
  54. if (i == q.cap) printf("FULL");
  55. q.count = i + 1;
  56. q.heap[i] = x;
  57. while (i > 0 && q.heap[(i - 1) / 2].k > q.heap[i].k) {
  58. q = swap(q, (i - 1) / 2, i);
  59. i = (i - 1) / 2;
  60. }
  61. return q;
  62. }
  63.  
  64. struct Help ExtractMin(struct Queue q)
  65. {
  66. if (q.count == 0) printf("NULL");
  67. return q.heap[0];
  68. }
  69.  
  70. int main()
  71. {
  72. int n, m, i, ans = 0, cur = 0, cluster = 0;
  73. struct Help x;
  74. scanf("%d\n", &n);
  75. scanf("%d\n", &m);
  76. int *data = (int*)malloc(2 * m * sizeof(int));
  77. for (i = 0; i < m; i++) {
  78. if (i != m - 1) {
  79. scanf("%d ", &data[2 * i]);
  80. scanf("%d\n", &data[2 * i + 1]);
  81. }
  82. else {
  83. scanf("%d ", &data[2 * i]);
  84. scanf("%d", &data[2 * i + 1]);
  85. }
  86. }
  87. struct Queue q = InitQueue(m);
  88. while (cur < 2 * m) {
  89. if (q.count > 0 && q.heap[0].k <= ans) {
  90. cluster--;
  91. q.count--;
  92. if (q.count > 0) {
  93. q.heap[0] = q.heap[q.count];
  94. q = heapify(0, q.count, q);
  95. }
  96. }
  97. if (data[cur] <= ans) {
  98. if (cluster < n) {
  99. cluster++;
  100. x.k = x.v = ans + data[cur + 1];
  101. q = Insert(q, x);
  102. cur += 2;
  103. }
  104. }
  105. ans++;
  106. }
  107. if (q.count > 0) ans = q.heap[q.count - 1].v;
  108. printf("%d\n", ans);
  109. free(data);
  110. free(q.heap);
  111. return 0;
  112. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement