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

#include <iostream>

void master()
{
   int n = NumberOfQueries();
   int sol[n];

   int nnodes  = NumberOfNodes();
   int curnode = 1;
   for( int i = 0; i < n; ++i ) {
      sol[i] = 0;
      PutChar(curnode, 'J');
      PutInt(curnode, i+1);
      Send(curnode);
      
      curnode += 1;
      if(curnode == nnodes) curnode = 1;
   }

   for( int i = 0; i < n; ++i ) {
      int id = Receive(-1);
      int j  = GetInt(id);
      int s  = GetInt(id);
      sol[j-1] = s;
   }

   for(int i = 1; i < nnodes; ++i ) {
      PutChar(i, 'Q');
      Send(i);
   }

   for(int i = 0; i < n; ++i ) {
      std::cout << sol[i] << std::endl;
   }
}

int solve(int q)
{
   int sol = 0;
   int from = QueryFrom(q);
   int to   = QueryTo(q);

   int prev1 = -1;
   int cur1  = from;
   int prev2 = -1;
   int cur2  = from;

   while( cur1 != to && cur2 != to ) {
      int n1 = FirstNeighbor(cur1);
      int n2 = SecondNeighbor(cur1);
      int m1 = SecondNeighbor(cur2);
      int m2 = FirstNeighbor(cur2);

      sol += 1;
      if( n1 != prev1 ) {
        prev1 = cur1;
        cur1  = n1;        
      }
      else {
        prev1 = cur1;
        cur1  = n2;
      }

      if( m1 != prev2 ) {
        prev2 = cur2;
        cur2  = m1;        
      }
      else {
        prev2 = cur2;
        cur2  = m2;
      }
   }

   return sol;
}

void worker()
{
   bool end = false;
   while(!end) {
      Receive(0);
      char cmd = GetChar(0);
      if( cmd == 'Q' ) {
         end = true;
      }
      if( cmd == 'J' ) {    
         int query = GetInt(0);
         int sol = solve(query);
         PutInt(0, query);
         PutInt(0, sol);
         Send(0);
      }
   }
}

int main()
{
   int id = MyNodeId();

   if( id == 0 ) {
      master();
   }
   else {
      worker();
   }
 
   return 0;
}