fork download
  1. /*
  2. Md Emam Hossain
  3. ID : 290
  4. Section : 09
  5. Intake : 52
  6. */
  7.  
  8. #include<bits/stdc++.h>
  9. using namespace std;
  10.  
  11. class process{
  12. public:
  13. string name;
  14. int bt;
  15. int prio;
  16. int arvt;
  17. int wt=0;
  18.  
  19. process(){
  20. cin>>name>>bt>>prio>>arvt;
  21. }
  22.  
  23. void show(){
  24. cout<<name<<" "<<bt<<" "<<prio<<" "<<arvt<<endl;
  25. }
  26. };
  27.  
  28.  
  29. int main(){
  30. int n;
  31. cin>>n;
  32.  
  33. vector<process> a(n);
  34.  
  35. //Sorting by arrival time
  36. for(int i=0;i<n;i++){
  37. for(int j=i+1;j<n;j++){
  38. if(a[j].arvt<a[i].arvt)swap(a[i],a[j]);
  39. if(a[j].arvt==a[i].arvt){
  40. if(a[j].prio<a[i].prio)
  41. swap(a[i],a[j]);
  42. }
  43. }
  44. }
  45.  
  46. vector<string> ans;
  47. vector<process> dem;
  48.  
  49. //preemptive step
  50. for(int i=0;i<n;i++){
  51. dem.push_back(a[i]);
  52.  
  53. //sorting demo
  54. int n2=dem.size();
  55.  
  56. //Sorting by priority
  57. for(int i=0;i<n2-1;i++){
  58. for(int j=i+1;j<n2;j++){
  59. if(dem[j].prio<dem[i].prio)swap(dem[i],dem[j]);
  60. }
  61. }
  62.  
  63. ans.push_back(dem[0].name);
  64.  
  65. dem[0].bt--;
  66. if(dem[0].bt==0)dem.erase(dem.begin()+0);
  67.  
  68. }
  69.  
  70. //non-preemptive step
  71. while(!dem.empty()){
  72. int n2=dem.size();
  73.  
  74. ans.push_back(dem[0].name);
  75.  
  76. dem[0].bt--;
  77. if(dem[0].bt==0)dem.erase(dem.begin()+0);
  78. }
  79.  
  80. //Gantt Chart
  81. cout<<"Gantt Chart "<<endl;
  82. for(int i=0;i<ans.size();i++){
  83.  
  84. cout<<ans[i]<<" ";
  85. }
  86.  
  87. cout<<endl<<endl<<"Waiting Times : "<<endl;
  88.  
  89. //finding waiting times for each process
  90. for(int i=0;i<n;i++){
  91. int ct=0;
  92. for(int j=0;j<ans.size();j++){
  93. if(a[i].name==ans[j])ct=j+1;
  94. }
  95.  
  96. a[i].wt=ct-(a[i].arvt+a[i].bt);
  97. }
  98.  
  99. //Calculating Avg. Waiting Times
  100. float wt=0;
  101.  
  102. for(int i=0;i<n;i++){
  103. cout<<a[i].name<<" "<<a[i].wt<<endl;
  104. wt+=1.0*a[i].wt;
  105. }
  106.  
  107. cout<<endl;
  108.  
  109. cout<<"Avg. Waitimg Time = "<<wt/n<<endl;
  110.  
  111. return 0;
  112. }
  113.  
  114. /*
  115. Sample Test Case
  116. 6
  117. p1 10 2 1
  118. p2 1 4 0
  119. p3 2 1 3
  120. p4 1 3 2
  121. p5 5 5 3
  122. p6 4 6 5
  123.  
  124. */
  125.  
Success #stdin #stdout 0.01s 5280KB
stdin
6
p1 10 2 1
p2 1 4 0
p3 2 1 3
p4 1 3 2
p5 5 5 3
p6 4 6 5
stdout
Gantt Chart 
p2 p1 p1 p3 p3 p1 p1 p1 p1 p1 p1 p1 p1 p4 p5 p5 p5 p5 p5 p6 p6 p6 p6 

Waiting Times : 
p2 0
p1 2
p4 11
p3 0
p5 11
p6 14

Avg. Waitimg Time = 6.33333