Preview:
#include <stdio.h>
#include <stdbool.h>
#define P 5
#define R 3
int available[R], max[P][R], allocation[P][R], need[P][R];
void calculate_need() {
    for (int i = 0; i < P; i++)
        for (int j = 0; j < R; j++)
            need[i][j] = max[i][j] - allocation[i][j];
}
bool is_safe(int safe_seq[]) {
    int work[R];
    bool finish[P] = {0};
    for (int i = 0; i < R; i++) work[i] = available[i];
    int count = 0;
    while (count < P) {
        bool found = false;
        for (int p = 0; p < P; p++) {
            if (!finish[p]) {
                int j;
                for (j = 0; j < R; j++)
                    if (need[p][j] > work[j]) break;
                if (j == R) {
                    for (int k = 0; k < R; k++) work[k] += allocation[p][k];
                    finish[p] = true;
                    safe_seq[count++] = p;
                    found = true;
                }
            }
        }
        if (!found) return false;
    }
    return true;
}
void input_data() {
    printf("Enter available resources: ");
    for (int i = 0; i < R; i++) scanf("%d", &available[i]);
    printf("Enter maximum demand:\n");
    for (int i = 0; i < P; i++) for (int j = 0; j < R; j++) scanf("%d", &max[i][j]);
    printf("Enter allocated resources:\n");
    for (int i = 0; i < P; i++) for (int j = 0; j < R; j++) scanf("%d", &allocation[i][j]);
}
int main() {
    input_data();
    calculate_need();
    int safe_seq[P];
    if (is_safe(safe_seq)) {
        printf("System is in a safe state.\nSafe sequence is: ");
        for (int i = 0; i < P; i++) printf("%d ", safe_seq[i]);
        printf("\n");
    } else {
        printf("System is not in a safe state.\n");
    }
    return 0;
}
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter