fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int main()
  4. {
  5. int n, m;
  6. n = 5; // Number of processes
  7. m = 3; // Number of resources
  8.  
  9. vector<vector<int>> Max
  10. {
  11. { 6, 5, 3 },
  12. { 4, 2, 1 },
  13. { 5, 1, 2 },
  14. { 1, 0, 2 },
  15. { 5, 2, 3 }
  16. };
  17. vector < vector<int>> Alloc
  18. {
  19. { 1, 0, 2 },
  20. { 3, 1, 0 },
  21. { 0, 1, 1 },
  22. { 1, 0, 1 },
  23. { 1, 0, 2 }
  24. };
  25. vector<int> Total { 7, 5, 7 }; // Total initial available resources
  26. vector<int>Avail(m); // Available resources after allocation
  27. for (int j = 0; j < m; j++)
  28. {
  29. int s = 0;
  30. for (int i = 0; i < n; i++)
  31. {
  32. s += Alloc[i][j];
  33. }
  34. Avail[j] = Total[j] - s;
  35. }
  36.  
  37. vector<int>Exec(n, 0);
  38. vector<vector<int>> Need( n , vector<int> (m));
  39. for (int i = 0; i < n; i++)
  40. {
  41. for (int j = 0; j < m; j++)
  42. Need[i][j] = Max[i][j] - Alloc[i][j];
  43. }
  44. int k, c = 0;
  45. vector<int>seq;
  46. while (c < n)
  47. {
  48. for (int i = 0; i < n; i++)
  49. {
  50. if (Exec[i] == 0)
  51. {
  52. int mark = 0;
  53. for (int j = 0; j < m; j++)
  54. {
  55. if (Need[i][j] > Avail[j])
  56. {
  57. mark = 1;
  58. break;
  59. }
  60. }
  61. if (mark == 0)
  62. {
  63. seq.push_back(i + 1);
  64. for (k = 0; k < m; k++)
  65. {
  66. Avail[k] += Alloc[i][k];
  67. }
  68. Exec[i] = 1;
  69. }
  70. }
  71. }
  72. c++;
  73. }
  74. cout << "The safe sequence of execution is ";
  75. for (int i = 0; i < n ; i++)
  76. {
  77. if (i == n - 1)
  78. cout << " P" << seq[i] << "\n";
  79. else
  80. cout << " P" << seq[i] << " ->";
  81. }
  82. }
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
The safe sequence of execution is  P2 -> P4 -> P5 -> P3 -> P1