#include #include using namespace std; // Function to check if a process can be safely executed bool canExecute(int process, vector &work, vector> &need) { for (int i = 0; i < work.size(); i++) { if (need[process][i] > work[i]) return false; } return true; } // Banker's Algorithm void bankersAlgorithm(int n, int m, vector> &allocation, vector> &max, vector &available) { vector work = available; vector finish(n, false); vector safeSequence; // Calculate the Need matrix vector> need(n, vector(m)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { need[i][j] = max[i][j] - allocation[i][j]; } } int count = 0; while (count < n) { bool found = false; for (int i = 0; i < n; i++) { if (!finish[i] && canExecute(i, work, need)) { for (int j = 0; j < m; j++) { work[j] += allocation[i][j]; } safeSequence.push_back(i); finish[i] = true; found = true; count++; } } if (!found) { cout << "System is not in a safe state. Deadlock may occur." << endl; return; } } cout << "System is in a safe state.\nSafe sequence: "; for (int i = 0; i < safeSequence.size(); i++) { cout << "P" << safeSequence[i]; if (i < safeSequence.size() - 1) cout << " -> "; } cout << endl; } int main() { int n, m; // Input number of processes and resources cout << "Enter the number of processes: "; cin >> n; cout << "Enter the number of resources: "; cin >> m; vector> allocation(n, vector(m)); vector> max(n, vector(m)); vector available(m); // Input Allocation matrix cout << "Enter the Allocation matrix (" << n << " x " << m << "):\n"; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> allocation[i][j]; } } // Input Max matrix cout << "Enter the Max matrix (" << n << " x " << m << "):\n"; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> max[i][j]; } } // Input Available resources cout << "Enter the Available resources (" << m << "): "; for (int i = 0; i < m; i++) { cin >> available[i]; } // Run Banker's Algorithm bankersAlgorithm(n, m, allocation, max, available); return 0; }