loulett

HW2_program_scheduler

Dec 1st, 2014
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.91 KB | None | 0 0
  1. #include <cstdio>
  2. #include <cstdlib>
  3.  
  4. struct Item
  5. {
  6.     int key;
  7.     float priority;
  8. };
  9.  
  10. struct PrQueue
  11. {
  12.     int size;
  13.     Item* queue;
  14. } queue;
  15.  
  16. void swap(Item &a, Item &b)
  17. {
  18.     Item t = a;
  19.     a = b;
  20.     b = t;
  21. }
  22.  
  23. void siftup(Item * heap, int i)
  24. {
  25.     while (heap[i].priority < heap[(i - 1) / 2].priority)
  26.     {
  27.         swap(heap[i], heap[(i - 1) / 2]);
  28.         i = (i - 1) / 2;
  29.     }
  30. }
  31.  
  32. void siftdown(Item * heap, int i, int n)
  33. {
  34.     int left = 0, right = 0, j = 0;
  35.     while (2 * i + 1 < n)
  36.     {
  37.         left = 2 * i + 1;
  38.         right = 2 * i + 2;
  39.         j = left;
  40.         if (right < n && heap[right].priority < heap[left].priority)
  41.             j = right;
  42.         if (heap[i].priority < heap[j].priority)
  43.             return;
  44.         swap(heap[i], heap[j]);
  45.         i = j;
  46.     }
  47. }
  48.  
  49. void add(Item * heap, Item i, int &n)
  50. {
  51.     n++;
  52.     heap[n - 1] = i;
  53.     siftup(heap, n - 1);
  54. }
  55.  
  56. int delete_min(Item *heap, int &n)
  57. {
  58.     int min = heap[0].key;
  59.     heap[0] = heap[n - 1];
  60.     n--;
  61.     siftdown(heap, 0, n);
  62.     return min;
  63. }
  64.  
  65. int size(PrQueue name)
  66. {
  67.     return name.size;
  68. }
  69.  
  70.  
  71. int main()
  72. {
  73.     int n = 0;
  74.     char a[7];
  75.     scanf("%d", &n);
  76.     queue.queue = (Item*)malloc(n * sizeof(Item));
  77.     queue.size = 0;
  78.     for (int i = 0; i < n; i++)
  79.     {
  80.         scanf("%s", a);
  81.         if (a[0] == 'A')
  82.         {
  83.             scanf("%i", &queue.queue[i].key);
  84.             scanf("%f", &queue.queue[i].priority);
  85.             add(queue.queue, queue.queue[i], queue.size);
  86.             printf("%f\n", queue.queue[0].priority);
  87.         }
  88.         else if (a[0] == 'P')
  89.         {
  90.             printf("%i\n", delete_min(queue.queue, queue.size));
  91.         }
  92.         else if (a[0] == 'F')
  93.         {
  94.             while (queue.size > 0)
  95.             {
  96.                 printf("%i\n", delete_min(queue.queue, queue.size));
  97.             }
  98.         }
  99.     }
  100.     return 0;
  101. }
Advertisement
Add Comment
Please, Sign In to add comment