#include "mpi.h"
#include <iostream>
int main(int argc, char *argv[]) {
int numtasks, rank, dest, source, tag = 1;
MPI_Status Stat;
int inmsg, outmsg;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
outmsg = rank;
if (rank % 2 == 0) {
dest = (rank + 1) % numtasks;
MPI_Send(&outmsg, 1, MPI_INT, dest, tag, MPI_COMM_WORLD);
source = (rank == 0) ? numtasks - 1 : rank - 1;
MPI_Recv(&inmsg, 1, MPI_INT, source, tag, MPI_COMM_WORLD, &Stat);
} else {
source = (rank == 0) ? numtasks - 1 : rank - 1;
MPI_Recv(&inmsg, 1, MPI_INT, source, tag, MPI_COMM_WORLD, &Stat);
dest = (rank + 1) % numtasks;
MPI_Send(&outmsg, 1, MPI_INT, dest, tag, MPI_COMM_WORLD);
}
std::cout << "Task " << rank << ": Received " << inmsg << std::endl;
MPI_Finalize();
return 0;
}
I2luY2x1ZGUgIm1waS5oIgojaW5jbHVkZSA8aW9zdHJlYW0+CgppbnQgbWFpbihpbnQgYXJnYywgY2hhciAqYXJndltdKSB7CiAgICBpbnQgbnVtdGFza3MsIHJhbmssIGRlc3QsIHNvdXJjZSwgdGFnID0gMTsKICAgIE1QSV9TdGF0dXMgU3RhdDsKICAgIGludCBpbm1zZywgb3V0bXNnOwogICAgTVBJX0luaXQoJmFyZ2MsICZhcmd2KTsKICAgIE1QSV9Db21tX3NpemUoTVBJX0NPTU1fV09STEQsICZudW10YXNrcyk7CiAgICBNUElfQ29tbV9yYW5rKE1QSV9DT01NX1dPUkxELCAmcmFuayk7CgogICAgb3V0bXNnID0gcmFuazsKICAgIGlmIChyYW5rICUgMiA9PSAwKSB7CiAgICAgICAgZGVzdCA9IChyYW5rICsgMSkgJSBudW10YXNrczsKICAgICAgICBNUElfU2VuZCgmb3V0bXNnLCAxLCBNUElfSU5ULCBkZXN0LCB0YWcsIE1QSV9DT01NX1dPUkxEKTsKICAgICAg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