#include <mpi.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
int myrank, root = 0;
MPI_Comm comm = MPI_COMM_WORLD;
// Initialize MPI environment
MPI_Init(&argc, &argv);
MPI_Comm_rank(comm, &myrank);
// Define arrays for input and output
double ain[30], aout[30];
int ind[30];
// Structure to hold value and rank
struct {
double val;
int rank;
} in[30], out[30];
// Initialize input array
for (int i = 0; i < 30; ++i) {
ain[i] = (double)(myrank + i); // Each process has its own set of values
in[i].val = ain[i];
in[i].rank = myrank;
}
// Perform reduction to find the maximum value and corresponding rank (MPI_MAXLOC)
MPI_Reduce(in, out, 30, MPI_DOUBLE_INT, MPI_MAXLOC, root, comm);
// Process root collects and prints the result
if (myrank == root) {
printf("Results from process %d:\n", root
); for (int i = 0; i < 30; ++i) {
aout[i] = out[i].val;
ind[i] = out[i].rank;
printf("Max value at index %d: %f from process %d\n", i
, aout
[i
], ind
[i
]); }
}
// Finalize MPI environment
MPI_Finalize();
return 0;
}
I2luY2x1ZGUgPG1waS5oPgojaW5jbHVkZSA8c3RkaW8uaD4KCmludCBtYWluKGludCBhcmdjLCBjaGFyICphcmd2W10pIHsKICAgIGludCBteXJhbmssIHJvb3QgPSAwOwogICAgTVBJX0NvbW0gY29tbSA9IE1QSV9DT01NX1dPUkxEOwoKICAgIC8vIEluaXRpYWxpemUgTVBJIGVudmlyb25tZW50CiAgICBNUElfSW5pdCgmYXJnYywgJmFyZ3YpOwogICAgTVBJX0NvbW1fcmFuayhjb21tLCAmbXlyYW5rKTsKCiAgICAvLyBEZWZpbmUgYXJyYXlzIGZvciBpbnB1dCBhbmQgb3V0cHV0CiAgICBkb3VibGUgYWluWzMwXSwgYW91dFszMF07CiAgICBpbnQgaW5kWzMwXTsKCiAgICAvLyBTdHJ1Y3R1cmUgdG8gaG9sZCB2YWx1ZSBhbmQgcmFuawogICAgc3RydWN0IHsKICAgICAgICBkb3VibGUgdmFsOwogICAgICAgIGludCByYW5rOwogICAgfSBpblszMF0sIG91dFszMF07CgogICAgLy8gSW5pdGlhbGl6ZSBpbnB1dCBhcnJheQogICAgZm9yIChpbnQgaSA9IDA7IGkgPCAzMDsgKytpKSB7CiAgICAgICAgYWluW2ldID0gKGRvdWJsZSkobXlyYW5rICsgaSk7ICAvLyBFYWNoIHByb2Nlc3MgaGFzIGl0cyBvd24gc2V0IG9mIHZhbHVlcwogICAgICAgIGluW2ldLnZhbCA9IGFpbltpXTsKICAgICAgICBpbltpXS5yYW5rID0gbXlyYW5rOwogICAgfQoKICAgIC8vIFBlcmZvcm0gcmVkdWN0aW9uIHRvIGZpbmQgdGhlIG1heGltdW0gdmFsdWUgYW5kIGNvcnJlc3BvbmRpbmcgcmFuayAoTVBJX01BWExPQykKICAgIE1QSV9SZWR1Y2UoaW4sIG91dCwgMzAsIE1QSV9ET1VCTEVfSU5ULCBNUElfTUFYTE9DLCByb290LCBjb21tKTsKCiAgICAvLyBQcm9jZXNzIHJvb3QgY29sbGVjdHMgYW5kIHByaW50cyB0aGUgcmVzdWx0CiAgICBpZiAobXlyYW5rID09IHJvb3QpIHsKICAgICAgICBwcmludGYoIlJlc3VsdHMgZnJvbSBwcm9jZXNzICVkOlxuIiwgcm9vdCk7CiAgICAgICAgZm9yIChpbnQgaSA9IDA7IGkgPCAzMDsgKytpKSB7CiAgICAgICAgICAgIGFvdXRbaV0gPSBvdXRbaV0udmFsOwogICAgICAgICAgICBpbmRbaV0gPSBvdXRbaV0ucmFuazsKICAgICAgICAgICAgcHJpbnRmKCJNYXggdmFsdWUgYXQgaW5kZXggJWQ6ICVmIGZyb20gcHJvY2VzcyAlZFxuIiwgaSwgYW91dFtpXSwgaW5kW2ldKTsKICAgICAgICB9CiAgICB9CgogICAgLy8gRmluYWxpemUgTVBJIGVudmlyb25tZW50CiAgICBNUElfRmluYWxpemUoKTsKICAgIHJldHVybiAwOwp9Cg==