#include<stdio.h>
#define m 3
#define n 5
struct REQUEST
{
int x;
int requ[m];
}req;
int allocation1[n][m],need1[n][m],available1[m];
int r,t;
void check(int allocation[][m],int available[m],int need[][m]);
void print(int allocation[][m],int available[m],int need[][m]);
main()
{
int i,j,p=0,q=0;
int allocation[n][m]={{0,1,0},{2,0,0},{3,0,2},{2,1,1},{0,0,2}};
int need[n][m]={{7,4,3},{1,2,2},{6,0,0},{0,1,1},{4,3,1}};
int available[m]={3,3,2};
print(allocation,available,need);
check(allocation,available,need);
if (t==1){do {
printf("\nplease input the NO. of process: ");
scanf("%d",&req.x);
r=req.x;
printf("please input the resouces of request A B C:");
for(j=0;j<m;j++)
scanf("%d",&req.requ[j]);
p=0;
q=0;
for(j=0;j<m;j++)
if(req.requ[j]>need[r][j]) p=1;
if(p) printf("\nThe resouces of request have been beyond the max number needed!");
else {
for(j=0;j<m;j++)
if(req.requ[j]>available[j]) q=1;
if(q) printf("\nThere are not enough available resouces!");
else {for(j=0;j<m;j++)
{available1[j]=available[j];
allocation1[r][j]=allocation[r][j];
need1[r][j]=need[r][j];
available[j]=available[j]-req.requ[j];
allocation[r][j]=allocation[r][j]+req.requ[j];
need[r][j]=need[r][j]-req.requ[j];
}
print(allocation,available,need);
check(allocation,available,need);
if(t==0){ for (j=0;j<m;j++)
{allocation[r][j]=allocation1[r][j];
need[r][j]=need1[r][j];
available[j]=available1[j]; }
printf("return:\n");
print(allocation,available,need);
}
}
}
printf("\nDo you want to continue? y or n?\n");
}while (getch()=='y');
}
}
void check(int allocation[][m],int available[m],int need[][m])
{int k,f=1,v=0,i,j ;
int a[n];
int finish[n]={0,0,0,0,0};
int work[m];
t=1;
for(i=0;i<m;i++)
work[i]=available[i];
k=n;
do{
for (i=0;i<n;i++)
{if (finish[i]==0)
{f=1;
for (j=0;j<m;j++)
if (need[i][j]>work[j])
f=0;
if(f==1)
{finish[i]=1;
a[v++]=i;
for (j=0;j<m;j++)
work[j]=work[j]+allocation[i][j];
}
}
}
k--;
}while(k>0);
f=1;
for (i=0;i<n;i++)
{
if (finish[i]==0)
{
f=0;
break;
}
}
if (f==0)
{printf("\nThis is unsafe and the system don't allocate resources to the process \n");
t=0;}
else
{printf("\nThe is safe and the safe number is:");
for (i=0;i<n;i++)
printf("%d ",a[i]);
}
}
void print(int allocation[][m],int available[m],int need[][m] )
{ int i,j;
int process[n];
printf("Process\t Allocation\t Need\n");
for (i=0;i<n;i++)
process[i]=i;
for(i=0;i<n;i++)
for(i=0;i<m;i++)
printf("%2d ",available[i]);
printf("\n");
}