@蕾蕾老师 补交作业,之前忘记提交了
#include <iostream> #include<stdio.h> #include<stdlib.h> using namespace std; # define m 50 int no1;//进程数 int no2;//资源数 int r; int allocation[m][m];//分配矩阵 int need[m][m];//需求矩阵 int available[m];//可用资源数目 int max[m][m]; //最大需求矩阵 char name1[m], name2[m]; void main() { void check(); void print(); int i, j, p = 0, q = 0; char c; int request[m], allocation[m][m],need1[m][m],available[m]; printf("银行家算法实现\n"); printf("请输入进程数:\n"); scanf("%d",&no2); printf("请输入Max矩阵:\n"); for (int i = 0; i<no1; i++) { for (int j = 0; j<no2; j++) { scanf("%d",&max[i][j]);//输入已知进程最大资源需求量 }; }; printf("请输入allocation 矩阵:\n"); for (int i = 0; i =no1) { printf("输入错误,请重新输入:\n"); continue; } else break; }; printf("\n请输入该进程所请求的资源数request[j]:\n"); for (int j = 0; j need[i][j]) p=1; //判断请求是否超过该进程所需要的资源数 if (p) { printf("请求资源超过该进程资源需求量,请求失败!\n"); } else { for (int j = 0; j<no2; j++) { if(request[j]>available[j]) q=1; //判断请求是否超过可用资源数 if (q) { printf("没有做够的资源分配,请求失败!\n"); } else { for (int j = 0; j<no2; j++) { available[j]=available[j]; allocation[i][j]=allocation[i][j]; need[i][j]=need[i][j]; }; printf("返回分配前资源数\n"); print(); }; }; } printf("\n你还要继续分配吗? Y or N ?\n"); //判断是否继续进行资源分配 c=getche();} }while (c=='y'||c=='Y'); } }; void check() //安全算法函数 { int k, f, v = 0, i, j; int work[m], a[m]; bool finish[m]; r = 1; for (i = 0; i < no1; i++) { finish[i] = false;//初始化京城均没得到足够资源数并完成 }; for (int i = 0; i < no2; i++) { work[i] = available[i];//work 表示课提供进程继续运行的各资源数 }; k = no1; do { for (i = 0; i < no1; i++) { if (finish[i] == false) { f = 1; for (j = 0; j < no2; j++) { if (need[i][j] > work[j]) { f = 0; } if (f == 1) { finish[i] = true; a[v++] = i; for (int j = 0; j < no2; j++) { work[j] += allocation[i][j]; } } } } } k--; } while (k > 0); f = 1; for (int i = 0; i < no1; i++) { if (finish[i] == false) { f = 0; break; } } if (f == 0) { printf("系统处在不安全状态!"); r = 0; } else { printf("\n系统当前为安全状态,安全序列为:\n"); for (int i = 0; i < no1; i++) { printf("p%d", a[i]); } } }; void print() { printf("\n"); printf("此时刻资源分配情况"); printf("进程名/号 | Max | Allocation | Need |\n"); for (int i = 0; i < no1; i++) { printf("p%d/%d", i, i); for (int j = 0; j < no2; j++) { printf("%d", max[i][j]); }; for (int j = 0; j < no2; j++) { printf("%d", allocation[i][j]); }; for (int j = 0; j < no2; j++) { printf("%d", need[i][j]); } printf("\n"); } printf("各类资源可利用的资源数为:"); for (int j = 0; j < no2; j++) { printf("%d", available[j]); } printf("\n"); }