# C_银行家算法的实现

#include <stdio.h>
#include <stdlib.h>
#define PRONUM 5
#define RESNUM 4
#define SAFE 1
#define UNSAFE 0

int max[PRONUM][RESNUM];
int available[RESNUM];
int allocation[PRONUM][RESNUM];
int need[PRONUM][RESNUM];
int work[RESNUM];
int request[RESNUM];
int processorder[PRONUM];

int smaller(int);
int SystemState();
void getNeed();
void init();

int main()
{
init();
FILE *pFile;
pFile = fopen("output.txt", "w");
if(SystemState() == SAFE)
{
printf("The system is in a safe state and the order is : \n");
int i = 0;
for(;i<PRONUM;i++) printf("%d ", processorder[i]);
fputs("The system is in a safe state\n", pFile);
}
else
{
printf("The sys is in an unsafe state\n");
fputs("The system is in a unsafe state\n", pFile);
}
fclose(pFile);
return 0;
}
void init()
{
char ans;
printf("Make a requeset?y/n");
ans = getchar();

int i, j;
for(i = 0;i<PRONUM;i++)
for(j = 0;j<RESNUM;j++)
scanf("%d", &allocation[i][j]);

for(i = 0;i<PRONUM;i++)
for(j = 0;j<RESNUM;j++)
scanf("%d", &max[i][j]);

for(i = 0;i<RESNUM;i++)
scanf("%d", &available[i]);
getNeed();

if(ans == 'y')
{
int process;
printf("Please input the num of the process that make a request\n");
scanf("%d", &process);
{
for(i = 0;i<RESNUM;i++)
scanf("%d", &request[i]);
}

for(i = 0;i<RESNUM;i++)
{
if(request[i] > available[i])
{
printf("The request is bigger than available, No request is fulfiled");
return ;
}
}

for(i = 0;i<RESNUM;i++)
{
need[process][i]-=request[i];
available[i]-=request[i];
allocation[process][i]+=request[i];
}
}
}

void getNeed()
{
int i, j;
for(i = 0;i<PRONUM;i++)
for(j = 0;j<RESNUM;j++)
need[i][j] = max[i][j] - allocation[i][j];
}

int SystemState()
{
int i, order;
for(i =0;i<PRONUM;i++)
work[i] = available[i];
int finish[PRONUM];
for(i = 0;i<PRONUM;i++) finish[i] = 0;

order = 0;
for(i = 0;i<PRONUM;i++)
{
if(!finish[i]&& smaller(i))
{
order++;
finish[i] = 1;
processorder[i] = order;
i = -1;
}
}

for(i = 0;i<PRONUM;i++)
{
if(!finish[i]) return UNSAFE;
}

return SAFE;
}

int smaller(int row)
{
int i = 0;
for(;i<RESNUM;i++)
{
if(need[row][i] > work[i])
return 0;
}
return 1;
}