#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>

#define SIZE 8 

int main(int argc, char *argv[]) {
    int rank, size;
    int numbers[SIZE][3];
    int lsum = 0, gsum = 0; //local_sum and global_sum
    int count_per_process;
    int *recvbuf; 

    // MPI environment
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);

    // Process 0 reads the input numbers
    if (rank == 0) {
        printf("Enter the numbers:\n"); //inputs 3 integers
        for (int i = 0; i < SIZE; i++) {
            scanf("%d %d %d", &numbers[i][0], &numbers[i][1], &numbers[i][2]);
        }
    }

    MPI_Bcast(numbers, SIZE * 3, MPI_INT, 0, MPI_COMM_WORLD);

    count_per_process = SIZE / size;

    // Each process calculates its local sum
    for (int i = rank * count_per_process; i < (rank + 1) * count_per_process; i++) {
        for (int j = 0; j < 3; j++) {
            lsum += numbers[i][j];
        }
        printf("Process %d partial sum of set %d: %d\n", rank, i, lsum);
    }

    // Reduce local sums to global sum at process 0
    MPI_Reduce(&lsum, &gsum, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);

    //prints the global sum
    if (rank == 0) {
        printf("Global sum: %d\n", gsum);
    }

    MPI_Finalize();
    return 0;
}
