Advertisement
ZOOOO

Untitled

Jan 27th, 2016
3,488
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. //кластер
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <stdio.h>
  5.  
  6. struct Elem {
  7. int end_time;
  8. };
  9.  
  10. typedef struct Elem Elem;
  11.  
  12. int cmp(Elem a, Elem b) {
  13. return b.end_time - a.end_time;
  14. }
  15.  
  16. struct PQ {
  17. Elem *heap;
  18. int cap;
  19. int count;
  20. };
  21.  
  22. typedef struct PQ PQ;
  23.  
  24. PQ *initPQ(int n) {
  25. PQ *q = malloc(sizeof(PQ));
  26. q->heap = malloc(sizeof(Elem) * n);
  27. q->cap = n;
  28. q->count = 0;
  29. return q;
  30. }
  31.  
  32. void freePQ(PQ *q) {
  33. free(q->heap);
  34. free(q);
  35. }
  36.  
  37. void addPQ(PQ *q, Elem n) {
  38. int i = q->count;
  39. if (q->count == q->cap)
  40. perror("overflow");
  41. q->count = i + 1;
  42. q->heap[i] = n;
  43. while (i > 0 && cmp(q->heap[(i - 1) / 2], q->heap[i]) < 0) {
  44. Elem tmp = q->heap[(i - 1) / 2];
  45. q->heap[(i - 1) / 2] = q->heap[i];
  46. q->heap[i] = tmp;
  47. i = (i - 1) / 2;
  48. }
  49. }
  50.  
  51. void heapify(int i, int n, Elem *heap) {
  52. while (1) {
  53. int l = 2 * i;
  54. int r = l + 1;
  55. int j = i;
  56. if (l < n && cmp(heap[i], heap[l]) < 0)
  57. i = l;
  58. if (r < n && cmp(heap[i], heap[r]) < 0)
  59. i = r;
  60. if (i == j)
  61. break;
  62. Elem tmp = heap[i];
  63. heap[i] = heap[j];
  64. heap[j] = tmp;
  65. }
  66. }
  67.  
  68. Elem popPQ(PQ *q) {
  69. if (q->count == 0)
  70. perror("empty");
  71. Elem p = q->heap[0];
  72. q->count--;
  73. if (q->count > 0) {
  74. q->heap[0] = q->heap[q->count];
  75. heapify(0, q->count, q->heap);
  76. }
  77. return p;
  78. }
  79.  
  80. int emptyPQ(PQ *q) {
  81. return q->count == 0;
  82. }
  83.  
  84. int main(int argc, char **argv) {
  85. int n;
  86. scanf("%d", &n);
  87. PQ *q = initPQ(n);
  88. int m;
  89. scanf("%d", &m);
  90. for(int i = 0; i < m; i++) {
  91. int start, duration;
  92. scanf("%d%d", &start, &duration);
  93. if(i < n) {
  94. addPQ(q, (Elem){start + duration});
  95. } else {
  96. Elem e = popPQ(q);
  97. if(e.end_time < start)
  98. addPQ(q, (Elem){start + duration});
  99. else
  100. addPQ(q, (Elem){e.end_time + duration});
  101. }
  102. }
  103. Elem last;
  104. while(!emptyPQ(q))
  105. last = popPQ(q);
  106. printf("%d", last.end_time);
  107. freePQ(q);
  108. return 0;
  109. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement