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

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

using namespace std;

int main()
{
	int begin = (MyNodeId() * Size()) / NumberOfNodes() + 1, end = ((MyNodeId() + 1) * Size()) / NumberOfNodes() + 1;
	long long int localMax = 0, front = 0, middle = 0, back = 0, completeSum = 0;
	long long int sum = ElementAt(begin);
	completeSum = sum;
	for(int i = begin + 1; i < end; i++)
	{
		if(sum < 0)
		{
			sum = 0;
		}
		sum += ElementAt(i);
		completeSum += ElementAt(i);
		if(sum > localMax)
		{
			localMax = sum;
		}
	}
	int iTop = begin, iLow = begin;
	long long int sumA = 0, sumB = 0, maxA = 0, maxB = 0;
	for(int i = begin; i < end; i++)
	{
		sumA += ElementAt(i);
		if(sumA > maxA)
		{
			iTop = i;
			maxA = sumA;
		}
	}
	for(int i = end - 1; i >= begin; i--)
	{
		sumB += ElementAt(i);
		if(sumB > maxB)
		{
			iLow = i;
			maxB = sumB;
		}
	}
	if(iTop <= iLow)
	{
		front = maxA;
		back = maxB;
		middle = completeSum - maxA - maxB;
	}
	else
	{
		front = completeSum - maxB;
		back = completeSum - maxA;
		middle = completeSum - front - back;
	}
	if(MyNodeId() > 0)
	{
	    PutLL(0, localMax);
	    PutLL(0, front);
	    PutLL(0, middle);
	    PutLL(0, back);
	    Send(0);
	}
	else
	{
		vector<long long int> vec(NumberOfNodes() * 3), vec2(NumberOfNodes());
		vec[0] = front;
		vec[1] = middle;
		vec[2] = back;
		vec2[0] = localMax;
    	for (int i = 1; i < NumberOfNodes(); ++i)
		{
      		int index = Receive(-1);
      		vec2[index] = GetLL(index);
      		vec[index * 3] = GetLL(index);
      		vec[index * 3 + 1] = GetLL(index);
      		vec[index * 3 + 2] = GetLL(index);
		}
		long long sum = vec[0], maxVal = 0;
		for(int i = 1; i < vec.size(); i++)
		{
			if(sum < 0)
			{
				sum = 0;
			}
			sum += vec[i];
			if(sum > maxVal)
			{
				maxVal = sum;
			}
		}
		for(int i = 0; i < vec2.size(); i++)
		{
			if(vec2[i] > maxVal)maxVal = vec2[i];
		}
		cout<<maxVal;
	}
	return 0;
}