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>
using namespace std;

int MyId = -1;
int Slaves = -1;

#define LASTSLAVE (MyId == Slaves)
#define MASTER 0
void init()
{
  MyId = MyNodeId();
  Slaves = NumberOfNodes() - 1;
}

void master()
{
  int sumall=0,maks=0,maksi=0;
  for (int i=1;i<=Slaves;i++)
  {
    Receive(i);
    int imaks = GetInt(i);
    int imaksi = GetInt(i);
    int isumall = GetInt(i);
    if (sumall+imaks > maks)
    {
       maks = sumall+imaks;
       maksi = imaksi;
    }
    sumall += isumall;
  }
  for (int i=1;i<=Slaves;i++)
  {
    PutInt(i,maksi);
    Send(i);
  }
  int mini=0;
  sumall = 0;
  for (int i=1;i<=Slaves;i++)
  {
    Receive(i);
    int imini = GetInt(i);
    int isumall = GetInt(i);
    if (mini > imini+sumall)
    {
      mini = imini + sumall;
    }
    sumall += isumall;
  }
/*
  cout << "maksi " << maksi<< endl;
  cout << "sumall " << sumall<< endl;
  cout << "mini " << mini<< endl;
  cout << "maks " << maks<< endl;
*/
  cout << maks - mini;
}

void slave()
{
  
  int s = Size();
  int l = s/Slaves;
  int p = l * (MyId-1)+1;
  int k = LASTSLAVE ? s : (l*MyId);
  l = k-p+1;
  int maks=0,maksi=-1;
  int mini=0;
  int sum=0;
  for (int i=p;i<=k;i++)
  {
    sum += ElementAt(i);
    if (sum > maks) 
    {
      maks = sum;
      maksi = i;
    }
  }
  int sumall = sum;
  PutInt(MASTER,maks);
  PutInt(MASTER,maksi);
  PutInt(MASTER,sumall);
  Send(MASTER);
  Receive(MASTER);
  maksi = GetInt(MASTER);
  sum=0;
  for (int i=p;i<=maksi && i <= k;i++)
  {
    sum += ElementAt(i);
    if (sum < mini) 
    {
      mini = sum;
    }
  }
/*  
  cout << "p " << p << endl;
  cout << "k " << k << endl;
  cout << "maksi " << maksi<< endl;
  cout << "sumall " << sumall<< endl;
  cout << "mini " << mini<< endl;
  cout << "maks " << maks<< endl;
*/  
  PutInt(MASTER,mini);
  PutInt(MASTER,sumall);
  Send(MASTER);
}

int main() {
  init();
  if (MyId == 0) master();
  else slave();
  return 0;
}