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
#include <algorithm>
#include <vector>
#include <cstdio>

#include "krazki.h"
#include "message.h"

const long long MAX = 1000000000000000050LL;

using namespace std;

int main() {
  int non = NumberOfNodes();
  int myid = MyNodeId();

  int ph = PipeHeight();
  int per_node = ph / non + 1;
  int nod = NumberOfDiscs();

  vector <long long> pipe;
  int start = myid * per_node + 1;
  int end = (myid + 1) * per_node + 1;
  for(int i = start; i < end; ++i) {
    if(i <= ph) {
      pipe.push_back(HoleDiameter(i));
    }
  }
  long long act = MAX;
  for(int i = 0; i < pipe.size(); ++i) {
    act = min(act, pipe[i]);
    pipe[i] = act; 
  }
  for(int i = myid + 1; i < non; ++i) {
    PutLL(i, act);
    Send(i);
  }
  long long n_act = MAX;
  for(int i = 0; i < myid; ++i) {
    Receive(i);
    n_act = min(n_act, GetLL(i));
  }

  for(int i = 0; i < pipe.size(); ++i) {
    pipe[i] = min(pipe[i], n_act);
  }
  
  int curr;
  int result = -1;
  if(myid == non - 1) {
    curr = 1;

    for(int i = pipe.size() - 1; i >= 0; --i) {
      if(curr <= nod and pipe[i] >= DiscDiameter(curr)) ++curr;
      if(curr > nod) {
        result = myid * per_node + i + 1;
        break;
      }
    }
    if(result != -1) {
      printf("%d\n", result);
    }  
    PutInt(myid - 1, curr);
    Send(myid - 1);
  } else {
    Receive(myid + 1);
    curr = GetInt(myid + 1);

    if(curr <= nod) {
      for(int i = pipe.size() - 1; i >= 0; --i) {
        if(curr <= nod and pipe[i] >= DiscDiameter(curr)) ++curr;
        if(curr > nod) {
          result = myid * per_node + i + 1;
          break;
        }
      }
    }
    if(result != -1) {
      printf("%d\n", result);
    } else if(myid == 0 and curr <= nod) {
      printf("0\n");
    } 

    if(myid > 0) {
      PutInt(myid - 1, curr);
      Send(myid - 1);
    }
  }
  return 0;
}