#define M 50
int allocation[M][M],need[M][M],available[M];
int n,m,r;
main()
{void check();
void print();
int i,j,p=0,q=0;
int req[M], allocation1[M][M],need1[M][M],available1[M];
printf("Please input the sum of processes:");
scanf("%d",&n);
for(j=0;j<m;j++)
scanf("%d",&need[i][j]);
printf("Available\n");
for (i=0;i<m;i++)
scanf("%d",&available[i]);
print();
check();
if (r==1)
{do {
printf("\nplease input the NO. of process: ");
scanf("%d",&i);
printf("please input the resources of request,A B C:");
for(j=0;j<m;j++)
scanf("%d",&req[j]);
p=0;
q=0;
for(j=0;j<m;j++)
if(req[j]>need[i][j]) p=1;
if(p) printf("The resources of request have been beyond the max number needed!");
else {
for(j=0;j<m;j++)
if(req[j]>available[j]) q=1;
if(q) printf("There are not enough available resources!");
else {for(j=0;j<m;j++)
{ available1[j]=available[j];
allocation1[i][j]=allocation[i][j];
need1[i][j]=need[i][j];
available[j]=available[j]-req[j];
allocation[i][j]=allocation[i][j]+req[j];
need[i][j]=need[i][j]-req[j];
}
print();
check();
if (r==0)
{for (j=0;j<m;j++)
{available[j]=available1[j];
allocation[i][j]=allocation1[i][j];
need[i][j]=need1[i][j];
}
printf("return:\n");
print();
}
}
}
printf("\nDo you want to continue? y or n?");
}while (getch()=='y');
}
}
void check()
{int k,f,v=0,i,j;
int work[M],a[M],finish[M];
r=1;
for(i=0;i<n;i++)
finish[i]=0;
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("This is unsafe \n");
r=0;
}
else
{
printf("This is safe and the safe number is:");
for (i=0;i<n;i++)
printf("%d ",a[i]);
}
}
void print()
{ int i,j;
int process[M];
printf("Process\t Allocation\t Need\n");
for (i=0;i<n;i++)
process[i]=i;
printf("\n");
}
printf("Available\n");
for(i=0;i<m;i++)
printf("%2d ",available[i]);
printf("\n");
}