#include #include using namespace std; void calculateNeed(vector>& need, vector>& max, vector>& allocation, int n, int m) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { need[i][j] = max[i][j] - allocation[i][j]; } } } bool isSafe(vector>& allocation, vector>& need, vector& available, int n, int m) { vector finish(n, false); vector safeSequence(n); vector work = available; int count = 0; while (count < n) { bool found = false; for (int i = 0; i < n; i++) { if (!finish[i]) { bool canProceed = true; for (int j = 0; j < m; j++) { if (need[i][j] > work[j]) { canProceed = false; break; } } if (canProceed) { for (int j = 0; j < m; j++) { work[j] += allocation[i][j]; } safeSequence[count++] = i; finish[i] = true; found = true; } } } if (!found) { cout << "System is not in a safe state!" << endl; return false; } } cout << "System is in a safe state. Safe sequence: "; for (int i = 0; i < n; i++) { cout << "P" << safeSequence[i]; if (i != n - 1) cout << " -> "; } cout << endl; return true; } int main() { int n, m; // Input the number of processes and resources cout << "Enter the number of processes: "; cin >> n; cout << "Enter the number of resource types: "; cin >> m; vector> allocation(n, vector(m)); vector> max(n, vector(m)); vector available(m); // Input Allocation Matrix cout << "Enter the Allocation Matrix:\n"; for (int i = 0; i < n; i++) { cout << "Process " << i << ": "; for (int j = 0; j < m; j++) { cin >> allocation[i][j]; } } // Input Max Matrix cout << "Enter the Max Matrix:\n"; for (int i = 0; i < n; i++) { cout << "Process " << i << ": "; for (int j = 0; j < m; j++) { cin >> max[i][j]; } } // Input Available Resources cout << "Enter the Available Resources: "; for (int i = 0; i < m; i++) { cin >> available[i]; } // Calculate Need Matrix vector> need(n, vector(m)); calculateNeed(need, max, allocation, n, m); // Check if the system is in a safe state isSafe(allocation, need, available, n, m); return 0; }