#include <stdio.
h>
#include <stdbool.h>
#define P 5    // Number of processes
#define R 3    // Number of resources
int   available[R]; // Available resources
int   maximum[P][R]; // Maximum demand of each process
int   allocation[P][R]; // Resources allocated to each process
int   need[P][R]; // Remaining needs for each process
// Function to calculate the need matrix
void calculateNeed() {
    for (int i = 0; i < P; i++) {
        for (int j = 0; j < R; j++) {
            need[i][j] = maximum[i][j] - allocation[i][j];
        }
    }
}
// Function to check if a process can finish (Banker's Algorithm)
bool isSafe() {
    int work[R];
    bool finish[P] = {false};
      // Initialize work
      for (int i = 0; i < R; i++) {
          work[i] = available[i];
      }
      // Try to find a process that can finish
      for (int count = 0; count < P; count++) {
          bool found = false;
          for (int p = 0; p < P; p++) {
              if (!finish[p]) {
                  // Check if process p can be completed with current work
                  bool canFinish = true;
                  for (int i = 0; i < R; i++) {
                      if (need[p][i] > work[i]) {
                          canFinish = false;
                          break;
                      }
                  }
                  if (canFinish) {
                      for (int i = 0; i < R; i++) {
                          work[i] += allocation[p][i]; // Add allocated resources to
work
                        }
                        finish[p] = true;
                        found = true;
                        break;
                  }
              }
          }
          if (!found) {
              return false;    // No process could finish
          }
      }
      return true;    // All processes can finish
}
int main() {
    // Input available resources
    printf("Enter the available resources: \n");
    for (int i = 0; i < R; i++) {
        scanf("%d", &available[i]);
    }
    // Input maximum resource demand for each process
    printf("Enter the maximum resource demand for each process: \n");
    for (int i = 0; i < P; i++) {
        for (int j = 0; j < R; j++) {
            scanf("%d", &maximum[i][j]);
        }
    }
    // Input the resources allocated to each process
    printf("Enter the allocated resources for each process: \n");
    for (int i = 0; i < P; i++) {
        for (int j = 0; j < R; j++) {
            scanf("%d", &allocation[i][j]);
        }
    }
    // Calculate the need matrix
    calculateNeed();
    // Check if the system is in a safe state
    if (isSafe()) {
        printf("The system is in a safe state.\n");
    } else {
        printf("The system is not in a safe state.\n");
    }
    return 0;
}