fork download
  1. import java.io.*;
  2. import java.util.*;
  3. import java.lang.*;
  4. class B
  5. {
  6. public static void main(String args[])
  7. {
  8. Scanner sc=new Scanner(System.in);
  9. System.out.println("Enter no. of processes:");
  10. int n=sc.nextInt();
  11. int i,j;
  12. System.out.println("Enter MAX matrix");
  13. int max[][]=new int[n][3];
  14. for(i=0;i<n;i++)
  15. {
  16. for(j=0;j<3;j++)
  17. {
  18. max[i][j]=sc.nextInt();
  19. }
  20. }
  21. System.out.println("Enter ALLOCATION matrix");
  22. int alloc[][]=new int[n][3];
  23. for(i=0;i<n;i++)
  24. {
  25. for(j=0;j<3;j++)
  26. {
  27. alloc[i][j]=sc.nextInt();
  28. }
  29. }
  30. System.out.println("Enter AVAILABLE row");
  31. int avail[]=new int[3];
  32. int work[]=new int[3];
  33. for(i=0;i<3;i++){
  34. avail[i]=sc.nextInt();
  35. work[i]=avail[i];
  36. }
  37. System.out.println("NEED matrix is:");
  38. int need[][]=new int[n][3];
  39. for(i=0;i<n;i++)
  40. {
  41. for(j=0;j<3;j++)
  42. {
  43. need[i][j]=Math.abs(max[i][j]-alloc[i][j]);
  44. }
  45. }
  46. for(i=0;i<n;i++)
  47. {
  48. for(j=0;j<3;j++)
  49. {
  50. System.out.print(need[i][j]+" ");
  51. }
  52. System.out.println();
  53. }
  54. boolean visited[]=new boolean[n];
  55. int safeq[]=new int[n];
  56. int k=0,count=0,c=0;
  57. boolean flag=false;
  58. while(count<n)
  59. {
  60. int initwork[]=work;
  61. c++;
  62. for(i=0;i<n;i++)
  63. {
  64. for(j=0;j<3;j++)
  65. {
  66. if(!visited[i])
  67. {
  68. if(need[i][j]>work[j])
  69. break;
  70. }
  71. }
  72. if(j==3 && !visited[i])
  73. {
  74. count++;
  75. visited[i]=true;
  76. safeq[k++]=i+1;
  77. for(j=0;j<3;j++)
  78. work[j]+=alloc[i][j];
  79. }
  80. }
  81. if(c==n)
  82. {
  83. for(j=0;j<3;j++)
  84. {
  85. if(work[j]!=initwork[j])
  86. break;
  87. }
  88. if(j==3)
  89. {
  90. flag=true;
  91. break;
  92. }
  93. }
  94. }
  95. if(flag==true)
  96. {
  97. System.out.println("Deadlock. No safe sequence is possible");
  98. }
  99. else
  100. {
  101. System.out.println("Safe sequence is: ");
  102. for(i=0;i<n;i++)
  103. System.out.print("P"+safeq[i]+" ");
  104. System.out.println();
  105. }
  106. }
  107. }
Success #stdin #stdout 0.07s 2184192KB
stdin
5
7 5 3 3 2 2 9 0 2 2 2 2 4 3 3
0 1 0 2 0 0 3 0 2 2 1 1 0 0 2
3 3 2
stdout
Enter no. of processes:
Enter MAX matrix
Enter ALLOCATION matrix
Enter AVAILABLE row
NEED matrix is:
7 4 3 
1 2 2 
6 0 0 
0 1 1 
4 3 1 
Safe sequence is: 
P2 P4 P5 P1 P3