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

#include <iostream>

using namespace std;

// function to read all input data
void readInputData(int* dataIn, int numOfData) {
	for (int i = 0; i < numOfData; ++i) {
		dataIn[i] = ElementAt(i+1);
	}
}

// function to sum up window elements
long long sumWindow(int* start, int len) {
	long long sumT = 0;
	for (int i = 0; i < len; ++i) {
		sumT += start[i];
	}
	return sumT;
}

int main(int argc, char* argv[]) {
	// read instances information
	int nodeId = MyNodeId();
	int numOfNodes = NumberOfNodes();
	// read size of input data
	int numOfData = Size();
	// check if subtable exists
	if (numOfData < 2) {
		if (nodeId == 0) cout << 0 << endl;
	} else if (numOfData < 3) { // if input vector has only two elements
		if (nodeId == 0) cout << ((ElementAt(1) < ElementAt(2)) ? ElementAt(2) : ElementAt(1)) << endl;
	} else {
		// calculate number of instances which will be used
		// maximum window has one element less than input vector
		int windowSize = 0;
		while (windowSize < 1 && numOfNodes > 1) {
			windowSize = (numOfData - 1) / numOfNodes;
			// if not all instances can have work then reduce their number
			if (windowSize < 1) numOfNodes--;
		}
		
		// only some of the instances will work
		if (numOfNodes > nodeId) {
			// read input data
			int* dataIn = new int[numOfData];
			readInputData(dataIn, numOfData);
			// auxiliary variable for window offset
			int windowOffset = 0;
			// auxiliary variables used to find the maximum sum
			long long windowSum = 0;
			long long maxSum = 0x8000000000000000; // minimum value of sum
			// for each instance generate proper window size
			for (windowSize = 1 + nodeId; windowSize < numOfData; windowSize += numOfNodes) {
				// clear previous window sum
				windowSum = 0;
				// shift each window trough input data and sum elements in it
				for (windowOffset = 0; windowSize + windowOffset <= numOfData; ++windowOffset) {
					windowSum = sumWindow((dataIn + windowOffset), windowSize);
					// if this sum is greater than current then replace it
					if (maxSum < windowSum) maxSum = windowSum;
				}
			}
			// clean up
			delete dataIn;
			
			// communicate with other instances
			if (nodeId > 0) {
				PutLL(0, maxSum);
				Send(0);
			} else {
				// read maximu sums from other instances
				for (int i = 1; i < numOfNodes; ++i) {
					Receive(i);
					windowSum = GetInt(i);
					// if this sum is greater than current then replace it
					if (maxSum < windowSum) maxSum = windowSum;
				}
				cout << maxSum << endl;
			}
		}
	}
	
	return 0;
}