#include <stdio.h>

void run_election(int votes[5][4], const char* label_case) {
    printf("=== %s ===\n", label_case);
    
    for (int i = 0; i < 5; i++) {
        printf("%d\t\t", i + 1);
        for (int j = 0; j < 4; j++) {
            printf("%d\t\t", votes[i][j]);
        }
        printf("\n");
    }
    
    int total_votes_candidate[4] = {0};
    int grand_total = 0;

    for (int j = 0; j < 4; j++) {
        for (int i = 0; i < 5; i++) {
            total_votes_candidate[j] += votes[i][j];
        }
        grand_total += total_votes_candidate[j];
    }

    char candidate_names[4] = {'A', 'B', 'C', 'D'};
    printf("\nHasil Perhitungan Suara:\n");
    for (int j = 0; j < 4; j++) {
        double percentage = ((double)total_votes_candidate[j] / grand_total) * 100.0;
        printf("Kandidat %c: %d suara (%.2f%%)\n", candidate_names[j], total_votes_candidate[j], percentage);
    }
    printf("Total Keseluruhan Suara: %d\n\n", grand_total);

    int winner_index = -1;
    for (int j = 0; j < 4; j++) {
        double percentage = ((double)total_votes_candidate[j] / grand_total) * 100.0;
        if (percentage > 50.0) {
            winner_index = j;
            break;
        }
    }

    if (winner_index != -1) {
        // c. Pemenang mutlak (> 50%)
        printf("PENGUMUMAN: Kandidat %c memenangkan pemilihan secara mutlak dengan perolehan di atas 50%% suara!\n\n", candidate_names[winner_index]);
    } else {
        int first_max = -1, second_max = -1;
        int first_idx = -1, second_idx = -1;

        for (int j = 0; j < 4; j++) {
            if (total_votes_candidate[j] > first_max) {
                second_max = first_max;
                second_idx = first_idx;
                first_max = total_votes_candidate[j];
                first_idx = j;
            } else if (total_votes_candidate[j] > second_max) {
                second_max = total_votes_candidate[j];
                second_idx = j;
            }
        }
        printf("PENGUMUMAN: Tidak ada kandidat yang meraih lebih dari 50%% suara.\n");
        printf("Terjadi pemilu lanjutan (runoff) antara Kandidat %c dan Kandidat %c.\n\n", candidate_names[first_idx], candidate_names[second_idx]);
    }
}

int main() {
    int original_votes[5][4] = {
        {192, 48, 206, 37},
        {147, 90, 312, 21},
        {186, 12, 121, 38},
        {114, 21, 408, 39},
        {267, 13, 382, 29}
    };

    run_election(original_votes, "Uji Coba 1: Data Asli");

    int modified_votes[5][4] = {
        {192, 48, 206, 37},
        {147, 90, 312, 21},
        {186, 12, 121, 38},
        {114, 21, 108, 39}, 
        {267, 13, 382, 29}
    };

    run_election(modified_votes, "Uji Coba 2: Kandidat C Mendapat 108 Suara di Precinct 4");

    return 0;
}