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

#define N 3

typedef struct {
    char name[10];
    int prio;       // 优先级
    int needtime;   // 需要运行时间
    int runtime;    // 已运行时间
    char state[10]; // 状态
} PCB;

PCB pcb[N];

// 按优先级从高到低排序
void sort_prio() {
    int i, j;
    PCB temp;
    for (i = 0; i < N-1; i++) {
        for (j = i+1; j < N; j++) {
            if (pcb[i].prio < pcb[j].prio) {
                temp = pcb[i];
                pcb[i] = pcb[j];
                pcb[j] = temp;
            }
        }
    }
}

// 显示格式完全匹配文档
void show() {
    printf("\n进程名\t优先级\t需要时间\t已运行时间\t状态\n");
    for (int i = 0; i < N; i++) {
        printf("%s\t%d\t%d\t\t%d\t\t%s\n",
            pcb[i].name,
            pcb[i].prio,
            pcb[i].needtime,
            pcb[i].runtime,
            pcb[i].state);
    }
}

int main() {
    // 固定进程：aa bb cc，和文档完全一致
    strcpy(pcb[0].name, "aa");
    pcb[0].prio = 3;
    pcb[0].needtime = 5;
    pcb[0].runtime = 0;
    strcpy(pcb[0].state, "就绪");

    strcpy(pcb[1].name, "bb");
    pcb[1].prio = 1;
    pcb[1].needtime = 3;
    pcb[1].runtime = 0;
    strcpy(pcb[1].state, "就绪");

    strcpy(pcb[2].name, "cc");
    pcb[2].prio = 5;  // 最高优先级
    pcb[2].needtime = 2;
    pcb[2].runtime = 0;
    strcpy(pcb[2].state, "就绪");

    printf("===== 进程调度实验：最高优先数优先 =====\n");
    sort_prio();
    show();

    int finish = 0;
    while (finish < N) {
        sort_prio();

        // 选优先级最高的进程运行
        int run_idx = -1;
        for (int i = 0; i < N; i++) {
            if (strcmp(pcb[i].state, "完成") != 0) {
                run_idx = i;
                break;
            }
        }

        // 标记运行
        strcpy(pcb[run_idx].state, "运行");
        printf("\n正在运行：%s\n", pcb[run_idx].name);
        show();

        // 运行一个时间单位
        pcb[run_idx].runtime++;

        // 判断是否完成
        if (pcb[run_idx].runtime >= pcb[run_idx].needtime) {
            strcpy(pcb[run_idx].state, "完成");
            finish++;
            printf("\n【%s】运行结束\n", pcb[run_idx].name);
        } else {
            strcpy(pcb[run_idx].state, "就绪");
        }
    }

    printf("\n===== 所有进程调度完成 =====\n");
    return 0;
}