#include <stdio.h>
#include <string.h>

#define MAX_PROCESS 5  // 最多5个进程

// 定义进程控制块PCB
typedef struct PCB {
    char name[10];     // 进程名
    int priority;      // 优先级
    int need_time;     // 需要运行时间
    int run_time;      // 已运行时间
    char state;        // 状态：R-运行，W-就绪，F-完成
} PCB;

PCB pcb[MAX_PROCESS];  // 进程数组
int process_num = 0;   // 实际进程数

// 初始化进程（直接写入输入数据，无需手动输入）
void initProcess() {
    // 实验示例输入：3个进程
    strcpy(pcb[0].name, "aa");
    pcb[0].priority = 3;
    pcb[0].need_time = 5;
    pcb[0].run_time = 0;
    pcb[0].state = 'W';

    strcpy(pcb[1].name, "bb");
    pcb[1].priority = 1;
    pcb[1].need_time = 8;
    pcb[1].run_time = 0;
    pcb[1].state = 'W';

    strcpy(pcb[2].name, "cc");
    pcb[2].priority = 5;
    pcb[2].need_time = 10;
    pcb[2].run_time = 0;
    pcb[2].state = 'W';

    process_num = 3;
}

// 查找当前优先级最高的就绪进程
int findMaxPriority() {
    int max = -1;
    int index = -1;
    for (int i = 0; i < process_num; i++) {
        if (pcb[i].state == 'W' && pcb[i].priority > max) {
            max = pcb[i].priority;
            index = i;
        }
    }
    return index;
}

// 显示所有进程信息
void showProcess() {
    printf("\n当前进程状态：\n");
    printf("进程名\t优先级\t需运行时间\t已运行时间\t状态\n");
    for (int i = 0; i < process_num; i++) {
        printf("%s\t%d\t%d\t\t%d\t\t%c\n",
               pcb[i].name, pcb[i].priority,
               pcb[i].need_time, pcb[i].run_time, pcb[i].state);
    }
}

// 进程调度主函数
void scheduleProcess() {
    int finish_count = 0;  // 完成进程数
    int current;           // 当前运行进程下标

    printf("===== 最高优先数优先调度算法开始 =====\n");
    showProcess();

    while (finish_count < process_num) {
        current = findMaxPriority();
        if (current == -1) break;  // 无就绪进程

        // 选中进程运行
        pcb[current].state = 'R';
        printf("\n运行进程：%s\n", pcb[current].name);
        pcb[current].run_time++;   // 运行时间+1

        // 运行完成
        if (pcb[current].run_time == pcb[current].need_time) {
            pcb[current].state = 'F';
            finish_count++;
            printf("进程 %s 运行完毕！\n", pcb[current].name);
        } else {
            // 动态优先级：运行一次优先级-1
            pcb[current].priority--;
            pcb[current].state = 'W';
        }
        showProcess();
    }
    printf("\n===== 所有进程调度完成 =====\n");
}

int main() {
    initProcess();    // 初始化并输入进程
    scheduleProcess();// 调度进程
    return 0;
}