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

struct Process {
    char name[10];
    int burst_time;
    int priority;
    int waiting_time;
    int turnaround_time;
};

void sortProcesses(struct Process p[], int n) {
    struct Process temp;
    for (int i = 0; i < n-1; i++) {
        for (int j = i+1; j < n; j++) {
            if (p[i].priority > p[j].priority) { // Sorting based on Priority
                temp = p[i];
                p[i] = p[j];
                p[j] = temp;
            }
        }
    }
}

void calculateTimes(struct Process p[], int n) {
    p[0].waiting_time = 0;
    p[0].turnaround_time = p[0].burst_time;

    for (int i = 1; i < n; i++) {
        p[i].waiting_time = p[i-1].waiting_time + p[i-1].burst_time;
        p[i].turnaround_time = p[i].waiting_time + p[i].burst_time;
    }
}

void display(struct Process p[], int n) {
    int total_waiting_time = 0, total_turnaround_time = 0;

    printf("\nProcess	Burst Time	Priority	Waiting Time	Turnaround Time\n");
    for (int i = 0; i < n; i++) {
        printf("%s	%d		%d		%d		%d\n", p[i].name, p[i].burst_time, p[i].priority, p[i].waiting_time, p[i].turnaround_time);
        total_waiting_time += p[i].waiting_time;
        total_turnaround_time += p[i].turnaround_time;
    }

    printf("\nTotal Waiting Time: %d", total_waiting_time);
    printf("\nAverage Waiting Time: %.2f", (float)total_waiting_time / n);
    printf("\nTotal Turnaround Time: %d", total_turnaround_time);
    printf("\nAverage Turnaround Time: %.2f\n", (float)total_turnaround_time / n);
}

int main() {
    int n;
    printf("Enter the number of processes: ");
    scanf("%d", &n);

    struct Process p[n];

    for (int i = 0; i < n; i++) {
        printf("\nEnter Process Name: ");
        scanf("%s", p[i].name);
        printf("Enter Burst Time: ");
        scanf("%d", &p[i].burst_time);
        printf("Enter Priority: ");
        scanf("%d", &p[i].priority);
    }

    sortProcesses(p, n);
    calculateTimes(p, n);
    display(p, n);

    return 0;
}
