#include "mpi.h"
#include <stdio.h>
int main ( int argc, char *argv[] ) {
	MPI_Status status;
	int ProcNum, ProcRank;
	int dim = 1000;
	MPI_Init ( &argc, &argv );
	MPI_Comm_size ( MPI_COMM_WORLD, &ProcNum);
	MPI_Comm_rank ( MPI_COMM_WORLD, &ProcRank);
	if(ProcRank == 0){

		double* A = new double[dim];
		double* B = new double[dim];
		for(int i = 0; i < dim; i++){
			A[i] = 1;
			B[i] = 1;
		}
		double C = 0, tmp = 0;
		for(int i = 1; i < ProcNum; i++){
			MPI_Send(A,dim,MPI_DOUBLE,i,i,MPI_COMM_WORLD);
			MPI_Send(B,dim,MPI_DOUBLE,i,i+5,MPI_COMM_WORLD);
		}
		for(int i = 1; i < ProcNum; i++){
			MPI_Recv(&tmp,1,MPI_DOUBLE,i,0,MPI_COMM_WORLD,&status);
			C += tmp;
		}
		printf("DOT-prod = %lf \n", C);
		delete [] A;
		delete [] B;
		A = NULL;
		B = NULL;

	}else{

		int d = dim;
		double* A = new double[d];
		double* B = new double[d];
		double C = 0.0;
		MPI_Recv(A,d,MPI_DOUBLE,0,ProcRank,MPI_COMM_WORLD,&status);
		MPI_Recv(B,d,MPI_DOUBLE,0,ProcRank+5,MPI_COMM_WORLD,&status);
		for(int i = (ProcRank - 1)*dim/4;i < ProcRank*dim/4; i++){
			C += A[i]*B[i];
		}
		MPI_Send(&C,1,MPI_DOUBLE,0,0,MPI_COMM_WORLD);
		delete [] A;
		delete [] B;
		A = NULL;
		B = NULL;

	}
	MPI_Finalize();
	return 0;
}
