酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

问题描述:假设系统中有a、b、c三类资源,且有四个并发进程,要求输入资源总量resource,以及每个进程运行所需的资源总量claim和已经分配得到的资源量allocation,利用银行家算法判断当前状态是否为安全状态,若为安全状态则给出一个安全序列。请用c语言编写 输入格式:程序要求输入五行,以回车符号作为分隔。第一行是三个整数,整数之间以空格作为分隔,表示a、b、c三类资源的总量。下面的四行分别表示每个进程运行所需的资源总量claim和已经分配得到的资源量allocation;每行有7个数据,以空格作为分隔。首先输入一个字符串(长度小于等于10),为进程名;第2、3、4个数据类型为整型,表示相应进程运行所需a、b、c三种资源总量claim;第5、6、7个数据类型为整型,表示相应进程已经分配得到的a、b、c三种资源量allocation。 输出格式:输出一个字符串。若当前为不安全状态则输出为”false”(不含双引号,所有字母皆为小写);若当前为安全状态则输出一个安全序列,进程名之间用空格作为分隔)

```c #include <stdio.h> #include <stdbool.h> #include <string.h> bool isSafeState(int available[], int max[][3], int allocated[][3], int n) { int need[n][3]; bool finish[n]; int work[3]; // Initialize need matrix for(int i=0; i<n; i++) { for(int j=0; j<3; j++) { need[i][j] = max[i][j] - allocated[i][j]; } finish[i] = false; } // Initialize work vector for(int i=0; i<3; i++) { work[i] = available[i]; } int safeSeq[n]; int count = 0; while (count < n) { bool found = false; for (int i = 0; i < n; i++) { if (finish[i] == false) { int j; for (j = 0; j < 3; j++) { if (need[i][j] > work[j]) { break; } } if (j == 3) { for (int k = 0; k < 3; k++) { work[k] += allocated[i][k]; } safeSeq[count++] = i; finish[i] = true; found = true; } } } if (found == false) { return false; } } printf("Safe Sequence is: "); for (int i = 0; i < n-1; i++) { printf("%d, ", safeSeq[i]); } printf("%d\n", safeSeq[n-1]); return true; } int main() { int resource[3]; int n = 4; // Number of processes // Input resource total availability scanf("%d %d %d", &resource[0], &resource[1], &resource[2]); int max[n][3], allocated[n][3]; char processName[n][10]; // Input max and allocated resources for each process for(int i=0; i<n; i++) { scanf("%s %d %d %d %d %d %d", processName[i], &max[i][0], &max[i][1], &max[i][2], &allocated[i][0], &allocated[i][1], &allocated[i][2]); } if(isSafeState(resource, max, allocated, n)) { printf("true\n"); } else { printf("false\n"); } return 0; } ``` [2024-11-14 16:44:57 | AI写代码神器 | 1390点数解答]

相关提问