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
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include "maklib.h"

#include "message.h"
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

typedef long long int lli;

int getElementAt(int pos) {
  return ElementAt(pos+1);
}

static void sendMessage(int target,lli left,lli right,lli total,lli localmax) {
  PutLL(target, left);
  PutLL(target, right);
  PutLL(target, total);
  PutLL(target, localmax);
  Send(target);
}

static void GetMessage(int instance, lli *left, lli *right, lli *total, lli *local) {
  Receive(instance);
  *left = GetLL(instance);
  *right = GetLL(instance);
  *total = GetLL(instance);
  *local = GetLL(instance);
}

static void processLocalPart(int first,int last, lli *leftmax,lli * rightmax, lli *total, lli* localmax) {
  lli currmaximum = 0;

  for (int i=first;i<last;++i) {
    lli nextv = getElementAt(i);

    *total += nextv;
    currmaximum += nextv;

    if (*total > *leftmax) {
      *leftmax = *total;
    }
    if (currmaximum < 0){
      currmaximum = 0;
    }
    if (currmaximum > *localmax) {
      *localmax = currmaximum;
    }
  }
  *rightmax = currmaximum;
}

static int numberOfNodes;
static void initNumberOfNodes(int size) {

  numberOfNodes = NumberOfNodes();
  if (numberOfNodes > size) {
    numberOfNodes = size;
  }
}


static lli processDataFromNodes() {
  lli leftmax=0,rightmax=0,total=0,localmax=0;
  lli best = 0;
  lli currmaximum = 0;

  for (int i=0;i<numberOfNodes;i++) {
    GetMessage(i, &leftmax, &rightmax, &total, &localmax);

    if (localmax > best) {
      best = localmax;
    }

    if (currmaximum + leftmax > best ) {
      best = currmaximum;
    }

    currmaximum += total;

    if (rightmax > currmaximum ) {
      currmaximum = rightmax;
    }

    if (currmaximum > best ) {
      best = currmaximum;
    }
  }
  return best;
}

int main() {
  int size = Size();

  lli leftmax=0,rightmax=0,total=0,localmax=0;

  initNumberOfNodes(size);

  if (MyNodeId() >= numberOfNodes) {
    return 0;
  }

  int range = (Size()+numberOfNodes-1) / numberOfNodes;

  int leftpos = range * MyNodeId();
  int rightpos = range * (MyNodeId()+1);

  if (rightpos > size) {
    rightpos = size;
  }

  processLocalPart(leftpos,rightpos, &leftmax, &rightmax, &total,&localmax);
  sendMessage(0,leftmax,rightmax,total,localmax);

  if (MyNodeId() == 0) {
    lli result = processDataFromNodes();
    cout << result;
  }

  return 0;
}