最笨的银行家算法c++
时间: 2023-11-18 16:02:51 浏览: 41
以下是最笨的银行家算法的C++代码实现:
```c++
#include <iostream>
using namespace std;
int main()
{
int n, m;
cout << "Enter the number of processes: ";
cin >> n;
cout << "Enter the number of resources: ";
cin >> m;
int available[m];
cout << "Enter the available resources: ";
for(int i=0; i<m; i++)
cin >> available[i];
int allocation[n][m], max[n][m], need[n][m];
cout << "Enter the allocation matrix: ";
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
cin >> allocation[i][j];
cout << "Enter the max matrix: ";
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
cin >> max[i][j];
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
need[i][j] = max[i][j] - allocation[i][j];
bool finish[n] = {0};
int safeSequence[n], work[m];
for(int i=0; i<m; i++)
work[i] = available[i];
int count = 0;
while(count < n)
{
bool found = false;
for(int i=0; i<n; i++)
{
if(!finish[i])
{
int j;
for(j=0; j<m; j++)
if(need[i][j] > work[j])
break;
if(j == m)
{
for(int k=0; k<m; k++)
work[k] += allocation[i][k];
safeSequence[count++] = i;
finish[i] = true;
found = true;
}
}
}
if(!found)
{
cout << "System is not in safe state";
exit(0);
}
}
cout << "System is in safe state.\nSafe sequence is: ";
for(int i=0; i<n; i++)
cout << safeSequence[i] << " ";
return 0;
}
```