#include "message.h"

#include <cstdio>
#include <cstdlib>

#include <unistd.h>


void floyd ( int n ) {
  int d[n][n];
  for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++)
      d[i][j] = rand ();

  for (int k = 0; k < n; k++)
    for (int i = 0; i < n; i++)
      for (int j = 0; j < n; j++)
        if (d[i][k] + d[k][j] < d[i][j])
          d[i][j] = d[i][k] + d[k][j];

  int sum = 0;
  for (int i = 0; i < n; i++)
    for (int j = 0; j < n; j++)
      sum += d[i][j];

  fprintf (stderr, "floyd (%d) = %d\n", n, sum);
}

class EarlyPrintNodes {
  public:
    EarlyPrintNodes () {
      int nodes = NumberOfNodes ();
      fprintf (stderr, "[pid #%d] nodes = %d\n", getpid(), nodes);
    }
};
EarlyPrintNodes doit;

int main() {
  int n = NumberOfNodes ();
  int k = MyNodeId ();
  // floyd (539 + k);
  if (k == 0) {
    // запускаем инта работяги
    // PutChar (k + 1, 17);
    // PutInt (k + 1, 239);
    PutInt (k + 1, 1287654);
    Send (k + 1);
  }
  while (true) {
    int r = Receive ();
    int value = GetInt (r);
    // fprintf (stderr, "[debug %d] received value %d from %d\n", k, value, r);
    if (value < 0) {
      return 0;
    }
    if (value == 0) {
      printf ("%d\n", k);
      for (int i = 0; i < n; i++) {
        if (i == k)
          continue;
        PutInt (i, -1);
        Send (i);
      }
      return 0;
    }
    if (value < 100)
      floyd (value);
    PutInt ((k + 1) % n, value - 1);
    Send ((k + 1) % n);
  }
  fprintf (stderr, "no way\n");
  return 0;
}
