zhangsongcui

Banker's algorithm

Nov 6th, 2011
635
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.95 KB | None | 0 0
  1. #include <iostream>
  2. #include <valarray>
  3. #include <vector>
  4. #include <list>
  5. using namespace std;
  6.  
  7. int main()
  8. {
  9.     using namespace std;
  10.     typedef list<vector<valarray<int> > > Matrix;
  11.     enum : Matrix::size_type { Allocation = 0, Max = 1, Need = 1 };
  12.     Matrix mat {
  13.         //  Allocation  ,   Max / Need
  14.         { { 0, 0, 1, 4 }, { 0, 6, 5, 6 } },
  15.         { { 1, 4, 3, 2 }, { 1, 9, 4, 2 } },
  16.         { { 1, 3, 5, 4 }, { 1, 3, 5, 6 } },
  17.         { { 1, 0, 0, 0 }, { 1, 7, 5, 9 } }
  18.     };
  19.     valarray<int> Available { 1, 5, 2, 0 };
  20.     for_each( mat.begin(), mat.end(), [] (Matrix::reference val) { val[Need] = val[Max] - val[Allocation]; } );
  21.     Matrix::iterator it;
  22.     while ( ( it = find_if( mat.begin(), mat.end(),
  23.             [&Available] (Matrix::const_reference val) { return (val[Need] <= Available).min() == true; } ) ) != mat.end() )
  24.         Available += (*it)[Allocation], mat.erase(it), it = mat.begin();
  25.     cout << (mat.empty() ? "Safe!" : "Unsafe!") << endl;
  26. }
  27.  
  28.  
Add Comment
Please, Sign In to add comment