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
#include <iostream>
#include <algorithm>

#include "message.h"
#include "maklib.h"

#define MIN_PER_WORKER  100000
#define LLZERO          (long long) 0

using namespace std;

int main(int argc, char const *argv[])
{
   int k = NumberOfNodes();
   int id = MyNodeId();
   int n = Size();
   // assert n >= 1

   // if input is too small, no need to use so many workers

   k = min(k, ((n - 1) / MIN_PER_WORKER) + 1);
   if (id == 0)
      cerr << "used workers: " << k << endl;

   if (id >= k)
      return 0;

   int range_len = (n - 1) / k + 1;

   int my_start = id * range_len + 1;
   int my_end = min(n, my_start + range_len - 1);

   // cerr << "start: " << my_start << " end: " << my_end << endl;

   long long sum = ElementAt(my_start);
   long long sum_from_left = sum; 
   long long my_max = max(LLZERO, sum);
   long long my_max_from_left = sum;

   for (int i = my_start + 1; i <= my_end; ++i)
   {
      long long akt = (long long) ElementAt(i);
      sum = max(LLZERO, sum + akt);
      my_max = max(my_max, sum);
      sum_from_left += akt;
      my_max_from_left = max(my_max_from_left, sum_from_left);
   }

   if (id == 0) {

      // Send right
      if (id + 1 < k)
      {
         PutLL(id + 1, sum);
         Send(id + 1);
      }

      // Start collectiong
      for (int i = 1; i < k; ++i)
      {
         int instance = Receive(-1);
         long long akt = GetLL(instance);
         my_max = max(my_max, akt);
      }

      // Final output
      cout << my_max << endl;
   } 
   else
   {
      // Receive from left
      int instance = Receive(id - 1);
      long long from_left = GetLL(instance);
      sum_from_left += from_left;
      my_max_from_left += from_left;

      // Send right
      if (id + 1 < k)
      {
         PutLL(id + 1, max(sum_from_left, sum));
         Send(id + 1);
      }

      // Send local max to collector
      my_max = max(my_max, my_max_from_left);
      PutLL(0, my_max);
      Send(0);
   }

   return 0;
}