include stdio include mpi define SIZE 40 define NUM_OF_FOODS 10 int ma

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <stdio.h>
#include <mpi.h>
#define SIZE 40
#define NUM_OF_FOODS 10
int main(int argc, char** argv)
{
int size, rank;
int i, j;
int next = 0;
int dp[SIZE + 1];
dp[0] = 0;
int p_b[size];
int p_e[size];
MPI_Status stat;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int wts[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int cost[10] = {1, 2, 3, 10, 5, 6, 7, 8, 9, 10};
if (rank != 0)
{
while (next != 1)
{
MPI_Recv(&next, 1, MPI_INT, rank - 1, 0, MPI_COMM_WORLD, &stat);
MPI_Recv(&p_b, size, MPI_INT, rank - 1, 1, MPI_COMM_WORLD, &stat);
MPI_Recv(&p_e, size, MPI_INT, rank - 1, 1, MPI_COMM_WORLD, &stat);
MPI_Recv(&dp, SIZE + 1, MPI_INT, rank - 1, 2, MPI_COMM_WORLD, &stat);
}
printf("Got it\n");
}
else
{
int mod = (SIZE + 1) % size;
int step = SIZE / size - 1;
p_b[0] = 0;
if (mod > 0) {
p_e[0] = step + 1;
mod--;
}
else
p_e[0] = step;
for (i = 0; i < size - 1; i++)
{
p_b[i + 1] = p_e[i] + 1;
if (mod > 0) {
p_e[i + 1] = p_b[i + 1] + step + 1;
mod--;
}
else
p_e[i + 1] = p_b[i + 1] + step;
}
}
printf("My pos start: %d end: %d\n", p_b[rank], p_e[rank]);
for (i = 1 + p_b[rank]; i <= p_e[rank]; i++)
{
dp[i] = dp[i - 1];
for (j = 0; j < NUM_OF_FOODS; j++)
{
if (wts[j] <= i)
{
dp[i] = (dp[i] < dp[i - wts[j]] + cost[j]) ? dp[i - wts[j]] + cost[j] : dp[i];
}
}
}
next = 1;
printf("S %d size: %d\n", rank, size);
if (rank == size - 1)
printf("%d\n", dp[SIZE]);
else {
printf("Send\n");
MPI_Send(&next, 1, MPI_INT, rank + 1, 0, MPI_COMM_WORLD);
MPI_Send(&p_b, size, MPI_INT, rank + 1, 1, MPI_COMM_WORLD);
MPI_Send(&p_e, size, MPI_INT, rank + 1, 1, MPI_COMM_WORLD);
MPI_Send(&dp, SIZE + 1, MPI_INT, rank + 1, 2, MPI_COMM_WORLD);
printf("Complited\n");
}
MPI_Finalize();
return 0;
}