Kaidul

Banker's Algorithm

Jan 22nd, 2013
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.26 KB | None | 0 0
  1. using namespace std;
  2. #include <iostream>
  3. #include <cstdio>
  4. #include <vector>
  5. #include <bitset>
  6. #include <cstring>
  7.  
  8.  
  9. #define M 10
  10.  
  11. vector <int> work;
  12. vector<int> :: iterator it;
  13. bitset <M> finish;
  14. int available[M], Max[M][M], allocation[M][M], need[M][M], instance[M];
  15. int nResource, nProcess;
  16. bool safeState;
  17.  
  18. bool terminable(int n) {
  19.     int temp;
  20.     for(int i =0; i< nResource; i++) {
  21.         temp = available[i] - need[n][i];
  22.         if(temp < 0) return false;
  23.     }
  24.     return true;
  25. }
  26.  
  27. int main() {
  28.     freopen("input.txt", "r", stdin);
  29.     while(cin >> nResource >> nProcess) {
  30.  
  31.         /** input starts **/
  32.         for (int i = 0; i < nResource; i++) cin >> instance[i];
  33.         for (int i=0; i < nProcess; i++) {
  34.             for (int j = 0; j < nResource; j++) {
  35.                 cin >> allocation[i][j];
  36.             }
  37.         }
  38.         for (int i=0; i < nProcess; i++) {
  39.             for (int j = 0; j < nResource; j++) {
  40.                 cin >> Max[i][j];
  41.             }
  42.         }
  43.         for (int i=0; i < nProcess; i++) {
  44.             for (int j = 0; j < nResource; j++) {
  45.                 need[i][j] = Max[i][j] - allocation[i][j];
  46.             }
  47.         }
  48.         for (int i = 0; i < nResource; i++) cin >> available[i];
  49.         /** input ends **/
  50.  
  51.         work.clear();
  52.         finish.reset(); //reseting all indices of finish to false
  53.         safeState = false;
  54.  
  55. loop:
  56.         for (int i =0; i < nProcess; i++) {
  57.             if(finish.test(i)) continue; //already terminated
  58.  
  59.             if(terminable(i)) {
  60.                 finish.set(i, 1);
  61.                 work.push_back(i);
  62.                 for(int j =0; j< nResource; j++) {
  63.                     available[j] -= need[i][j];
  64.                     available[j] += Max[i][j];
  65.                 }
  66.             }
  67.             if(work.size() == nProcess) { //all processes are relaxed/terminated
  68.                 safeState = true;
  69.                 break;
  70.             }
  71.  
  72.             if(i == nProcess-1) goto loop;
  73.         }
  74.  
  75.         if(safeState) {
  76.             cout << "The system is in safe state\n";
  77.             for (it = work.begin(); it != work.end(); it++) cout << *it << " ";
  78.             cout << "\n";
  79.         } else cout << "The system is in unsafe state\n";
  80.     }
  81.     return 0;
  82. }
Add Comment
Please, Sign In to add comment