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

#include <algorithm>
#include <cstdio>
#include <vector>

using namespace std;

typedef long long LL;


int main() {
  int nodes = NumberOfNodes();
  int node_id = MyNodeId();

  int n = GetN();
  int share = (n-1) / nodes + 1;
  int a = share * node_id;
  int b = share * (node_id + 1);
  a = min(a, n);
  b = min(b, n);

  vector<int> values;
  for (int i=a; i<b; ++i) {
    values.push_back(GetTaste(i));
  }

  // Prefix sum - exclusive.
  vector<LL> pref;
  LL sum = 0;
  pref.push_back(sum);
  for (int i=a; i<b; ++i) {
    sum += values[i-a];
    pref.push_back(sum);
  }

  LL max_pref_sum = 0;
  if (node_id != 0) {
    Receive(node_id-1);
    LL pref_sum = GetLL(node_id-1);
    max_pref_sum = GetLL(node_id-1);
    for (LL& val : pref) {
      val += pref_sum;
    }
  }

  if (node_id+1 != nodes) {
    PutLL(node_id+1, pref.back());
  }
  
  for (int i=a; i<b; ++i) {
    max_pref_sum = max(max_pref_sum, pref[i-a]);
    pref[i-a] = max_pref_sum;
  }

  if (node_id+1 != nodes) {
    PutLL(node_id+1, max_pref_sum);
    Send(node_id+1);
  }

  // Suffix sum - inclusive
  vector<LL> suff(b-a);
  sum = 0;
  for (int i=b-1; i>=a; --i) {
    sum += values[i-a];
    suff[i-a] = sum;
  }

  LL max_suff_sum = 0;
  if (node_id+1 != nodes) {
    Receive(node_id+1);
    LL suff_sum = GetLL(node_id+1);
    max_suff_sum = GetLL(node_id+1);
    for (LL& val : suff) {
      val += suff_sum;
    }
  }

  if (node_id != 0) {
    if (suff.empty()) {
      PutLL(node_id-1, 0ll);
    } else {
      PutLL(node_id-1, suff[0]);
    }
  }
  
  for (int i=b-1; i>=a; --i) {
    max_suff_sum = max(max_suff_sum, suff[i-a]);
    suff[i-a] = max_suff_sum;
  }

  if (node_id != 0) {
    PutLL(node_id-1, max_suff_sum);
    Send(node_id-1);
  }

  // Join
  LL result = 0;
  for (int i=a; i<b; ++i) {
    result = max(result, pref[i-a] + suff[i-a]);
  }
  if (node_id != 0) {
    PutLL(0, result);
    Send(0);
  } else {
    for (int i=1; i<nodes; ++i) {
      Receive(i);
      result = max(result, GetLL(i));
    }
    printf("%lld\n", result);
  }
  return 0;
};