```c #include <stdio.h> #include <stdbool.h> // 计算还需要的资源 void calculateNeed(int need[][3], int claim[][3], int allocation[][3], int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < 3; j++) { need[i][j] = claim[i][j] - allocation[i][j]; } } } // 检查资源是否足够 bool isSafe(int available[], int need[][3], int allocation[][3], int n, int work[], int finish[]) { for (int i = 0; i < n; i++) { if (finish[i] == 0) { bool flag = true; for (int j = 0; j < 3; j++) { if (need[i][j] > work[j]) { flag = false; break; } } if (flag) { for (int j = 0; j < 3; j++) { work[j] += allocation[i][j]; } finish[i] = 1; return true; } } } return false; } // 银行家算法 bool bankerAlgorithm(int available[], int claim[][3], int allocation[][3], int n) { int need[n][3]; calculateNeed(need, claim, allocation, n); int work[3]; for (int i = 0; i < 3; i++) { work[i] = available[i]; } int finish[n]; for (int i = 0; i < n; i++) { finish[i] = 0; } bool found = true; while (found) { found = isSafe(work, need, allocation, n, work, finish); } for (int i = 0; i < n; i++) { if (finish[i] == 0) { return false; } } return true; } // 打印安全序列 void printSafeSequence(int claim[][3], int allocation[][3], int n) { int available[3]; int need[n][3]; calculateNeed(need, claim, allocation, n); int work[3]; for (int i = 0; i < 3; i++) { work[i] = available[i]; } int finish[n]; for (int i = 0; i < n; i++) { finish[i] = 0; } bool found = true; int sequence[n]; int index = 0; while (found) { found = isSafe(work, need, allocation, n, work, finish); for (int i = 0; i < n; i++) { if (finish[i] == 1) { continue; } bool flag = true; for (int j = 0; j < 3; j++) { if (need[i][j] > work[j]) { flag = false; break; } } if (flag) { sequence[index++] = i; for (int j = 0; j < 3; j++) { work[j] += allocation[i][j]; } finish[i] = 1; } } } for (int i = 0; i < n; i++) { printf("%s ", (i == 0)? "" : " "); switch (sequence[i]) { case 0: printf("P0"); break; case 1: printf("P1"); break; case 2: printf("P2"); break; case 3: printf("P3"); break; } } } int main() { int resource[3]; scanf("%d %d %d", &resource[0], &resource[1], &resource[2]); int claim[4][3], allocation[4][3]; char processName[4][10]; for (int i = 0; i < 4; i++) { scanf("%s %d %d %d %d %d %d", processName[i], &claim[i][0], &claim[i][1], &claim[i][2], &allocation[i][0], &allocation[i][1], &allocation[i][2]); } if (bankerAlgorithm(resource, claim, allocation, 4)) { printSafeSequence(claim, allocation, 4); } else { printf("false"); } return 0; } ``` [2024-11-14 16:47:16 | AI写代码神器 | 1153点数解答]