Advertisement
shabbyheart

Job sequence with deadline greedy algorithm

Dec 21st, 2019
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.81 KB | None | 0 0
  1. /*
  2. input
  3. 5
  4. 15 3
  5. 10 1
  6. 5 2
  7. 1 2
  8. 20 2
  9. */
  10.  
  11.  
  12.  
  13. #include<bits/stdc++.h>
  14. using namespace std;
  15. int d[100],p[100],j[100];
  16. int sequence[100];
  17.  
  18. int js(int n)
  19. {
  20.     for(int i =1;i<=n;i++)
  21.     {
  22.         for(int j =1;j<=n;j++)
  23.         {
  24.             if(p[j]<p[j+1])
  25.             {
  26.                 swap(p[j],p[j+1]);
  27.                 swap(d[j],d[j+1]);
  28.                 swap(sequence[j],sequence[j+1]);
  29.             }
  30.         }
  31.  
  32.     }
  33.  
  34.  
  35.     d[0] = j[0] = 0;
  36.     j[1]  = 1;
  37.     int k = 1;
  38.     for(int i = 2;i<=n;i++)
  39.     {
  40.         int r = k;
  41.         while(d[i]<d[j[r]] && d[j[r]]!=r)
  42.         {
  43.             r = r-1;
  44.         }
  45.         if(d[i]>=d[j[r]] && d[i]>r)
  46.         {
  47.             for(int q = k;q>=r+1;q--)
  48.                 j[q+1] = j[q];
  49.             j[r+1] = i;
  50.             k = k+1;
  51.         }
  52.     }
  53.     return k;
  54. }
  55.  
  56. int main()
  57. {
  58.     int original_profit_sequence[100],original_deadline_sequence[100];
  59.     int n;
  60.     freopen("in.txt","r",stdin);
  61.     cin>>n;
  62.     for(int i =1;i<=n;i++)
  63.         cin>>p[i]>>d[i];
  64.     cout<<endl;
  65.     for(int i=1;i<=n;i++)
  66.     {
  67.         sequence[i] = i;
  68.         original_profit_sequence[i] = p[i];
  69.         original_deadline_sequence[i] =d[i];
  70.  
  71.     }
  72.  
  73.     cout<<"Before Sorting: "<<endl;
  74.     for(int i=1;i<=n;i++)
  75.     {
  76.         cout<<" "<<p[i]<<" "<<d[i]<<endl;
  77.     }
  78.  
  79.     int k = js(n);
  80.     cout<<"After Sorting: "<<endl;
  81.     for(int i =1;i<=n;i++)
  82.         cout<<p[i]<<" "<<d[i]<<endl;
  83.     cout<<endl;
  84.     cout<<endl;
  85.     cout<<"Added job of original sequence: "<<endl;
  86.     for(int i =1;i<=k;i++)
  87.     {
  88.         cout<<sequence[j[i]]<<" "<<original_profit_sequence[sequence[j[i]]]<<" "<<original_deadline_sequence[sequence[j[i]]]<<endl;
  89.  
  90.     }
  91.     cout<<endl<<"Sequence after sorting: ";
  92.     for(int i =1;i<=k;i++)
  93.     {
  94.          cout<<j[i]<<" ";
  95.     }
  96.  
  97.  
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement