#include <stdio.h>
#define MAX_PROCESS 10
#define MAX_RESOURCE 10
int main() {
int n, m; // Number of processes and resources
int allocation[MAX_PROCESS][MAX_RESOURCE]; // Allocation Matrix
int max[MAX_PROCESS][MAX_RESOURCE]; // Maximum Need Matrix
int available[MAX_RESOURCE]; // Available Resources
int need[MAX_PROCESS][MAX_RESOURCE]; // Need Matrix
int finish[MAX_PROCESS]; // Finish array (0 = not finished, 1 = finished)
int safeSeq[MAX_PROCESS]; // Safe sequence array
int work[MAX_RESOURCE]; // Work array
printf("Enter the number of processes: ");
scanf("%d", &n);
printf("Enter the number of resources: ");
scanf("%d", &m);
printf("Enter the allocation matrix (%d x %d):\n", n, m);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
scanf("%d", &allocation[i][j]);
}
}
printf("Enter the maximum matrix (%d x %d):\n", n, m);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
scanf("%d", &max[i][j]);
}
}
printf("Enter the available resources (%d elements):\n", m);
for (int i = 0; i < m; ++i) {
scanf("%d", &available[i]);
}
// Initialize finish array and calculate need matrix
for (int i = 0; i < n; ++i) {
finish[i] = 0;
for (int j = 0; j < m; ++j) {
need[i][j] = max[i][j] - allocation[i][j];
}
}
// Initialize work array with available resources
for (int i = 0; i < m; ++i) {
work[i] = available[i];
}
int count = 0; // Number of processes in the safe sequence
int safeIndex = 0;
// Find a safe sequence
while (count < n) {
int found = 0; // Flag to indicate if a process was found in this iteration
for (int i = 0; i < n; ++i) {
if (finish[i] == 0) { // If process i is not finished
int canExecute = 1; // Assume process i can execute
for (int j = 0; j < m; ++j) {
if (need[i][j] > work[j]) { // If need is greater than work
canExecute = 0;
break;
}
}
if (canExecute) { // If process i can execute
for (int j = 0; j < m; ++j) {
work[j] += allocation[i][j]; // Release resources
}
finish[i] = 1;
safeSeq[safeIndex++] = i;
found = 1;
count++;
}
}
}
if (!found) { // If no process was found in this iteration, system is unsafe
printf("The system is in an UNSAFE state.\n");
return 0;
}
}
// Print the safe sequence
printf("The system is in a SAFE state.\n");
printf("Following is the SAFE Sequence: ");
for (int i = 0; i < n - 1; ++i) {
printf("P%d -> ", safeSeq[i]);
}
printf("P%d\n", safeSeq[n - 1]);
return 0;
}