fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct Process {
  5. long long id;
  6. int atime;
  7. int btime;
  8. int wtime;
  9. int ttime;
  10. int st_time;
  11. int comp_time;
  12. };
  13.  
  14. bool comparearrival(Process a, Process b) {
  15. return a.atime < b.atime;
  16. }
  17. void calculatetimes(vector<Process>& process) {
  18. int curr_time = 0;
  19. for (auto& p : process) {
  20. if (curr_time < p.atime)
  21. curr_time = p.atime;
  22. p.st_time = curr_time;
  23. p.wtime = p.st_time - p.atime;
  24. p.comp_time = p.st_time + p.btime;
  25. p.ttime = p.comp_time - p.atime;
  26. curr_time = p.comp_time;
  27. }
  28. }
  29.  
  30. void calculate_average(const vector<Process>& process) {
  31. float total_waiting = 0, total_turnaround = 0;
  32. for (const auto& p : process) {
  33. total_waiting += p.wtime;
  34. total_turnaround += p.ttime;
  35. }
  36. cout << fixed << setprecision(2);
  37. cout << "\nAverage waiting time: " << total_waiting / process.size() << "\n";
  38. cout << "Average turnaround time: " << total_turnaround / process.size();
  39. }
  40.  
  41. int main() {
  42. int n;
  43. cout << "process: ";
  44. cin >> n;
  45.  
  46. vector<Process> process(n);
  47. for (int i = 0; i < n; ++i) {
  48. process[i].id = i + 1;
  49. cout << "Arrival time of Process " << i + 1 << ": ";
  50. cin >> process[i].atime;
  51. cout << "Burst time of Process " << i + 1 << ": ";
  52. cin >> process[i].btime;
  53. }
  54.  
  55. sort(process.begin(), process.end(), comparearrival);
  56.  
  57. cout << "\norder: ";
  58. for (const auto& p : process)
  59. cout << "P" << p.id << " ";
  60. cout << "\n";
  61.  
  62. calculatetimes(process);
  63. calculate_average(process);
  64.  
  65. return 0;
  66. }
  67.  
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
process: 
order: 

Average waiting time: -nan
Average turnaround time: -nan