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
#include "maklib.h"
#include "message.h"

#include <algorithm>
#include <iostream>
#include <cmath>
#include <vector>

using namespace std;

vector<long long> comp(int begin, int end) {
  vector<long long> result(4);

  long long sum = 0;
  long long left = 0;

  for (int i = begin; i <= end; ++i) {
    sum += ElementAt(i);
    left = max(sum, left);
  }

  result[0] = sum;
  result[1] = left;

  long long right = 0;
  sum = 0;

  for (int i = end; i >= begin; --i) {
    sum += ElementAt(i);
    right = max(right, sum);
  }

  result[2] = right;

  long long max_so_far = 0;
  long long max_ending_here = 0;

  for (int i = begin; i <= end; i++) {
    if (max_ending_here < 0)
      max_ending_here = ElementAt(i);
    else
      max_ending_here += ElementAt(i);
 
    if (max_ending_here >= max_so_far )
      max_so_far  = max_ending_here;
  }

  result[3] = max_so_far;

  //cout << result[0] << " " << result[1] << " " << result[2] << " " << result[3] << endl;

  return result;
}

int main() {

  if (NumberOfNodes() > Size()) {
    if (MyNodeId() > 0) return 0;

    cout << comp(1, Size())[3] << endl;
    return 0;
  }

  int partcount = ceil((float)Size() / (float)NumberOfNodes());

  int begin = MyNodeId()*partcount+1;
  int end = (MyNodeId()+1)*partcount;
  end = min(Size(), end);
  //cout << "calculating from " << begin << " to " << end << endl;
  //for (int i = begin; i <= end; ++i)
  //  cout << ElementAt(i) << " ";
  //cout << endl;
  vector<long long> r = comp(begin, end);

  if (MyNodeId()> 0) {
    PutLL(0, r[0]);
    PutLL(0, r[1]);
    PutLL(0, r[2]);
    PutLL(0, r[3]);
    Send(0);
  } else {
    vector<vector<long long> > data(NumberOfNodes(), vector<long long>(4));
    data[0] = r;
    for (int i = 1; i < NumberOfNodes(); ++i) {
      Receive(i);
      data[i][0] = GetLL(i);
      data[i][1] = GetLL(i);
      data[i][2] = GetLL(i);
      data[i][3] = GetLL(i);
    }

    long long m = data[0][3];
    for (int i = 1; i < data.size(); ++i)
      m = max(m, data[i][3]);

    for (int i = 0 ; i < data.size(); ++i) {
      for (int k = i+1; k < data.size(); ++k) {
        long long s = data[i][2];

        for (int l = i+1; l < k; ++l) {
          s += data[l][0];
        }

        s += data[k][1];

        //cout << "i " << i << " k " << k << " s " << s << endl;
        
        m = max(m, s);
      }
    }

    cout << m << endl;
  }

}