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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <random>
#include <set>
#include <unordered_set>
#include <utility>
#include <vector>
#include "message.h"
#include "kollib.h"
using namespace std;

#define REP(i,n) for(int i=0;i<(n);++i)

namespace {

const int SINGLE_NODE_THRESHOLD = 1000000;
const int MINIMUM_PER_NODE = 100000;
const int MIN_TEAM = 4;
const int SAMPLES_PER_NODE = 100;
const int PREDICTION_HISTORY = 10;
const int PREDICTION_FLIP = 8;
const int SEED = 834795938;

template<class T> inline int size(const T&c) { return c.size(); }

mt19937 gRNG(SEED);

inline int Random(int n) {
  return uniform_int_distribution<>(0,n-1)(gRNG);
}

struct HashFunction {
  unsigned a;
  int sh;
  unsigned Apply(unsigned x) const { return (a*x)>>sh; }
};

HashFunction RandomHashFunction(int bits) {
  HashFunction hf;
  hf.sh = 32-bits;
  hf.a = gRNG() | 1u;
  return hf;
}

class SimplePerfectHashSet {
 public:
  explicit SimplePerfectHashSet(const vector<int> &v);
  bool Contains(int) const;
 private:
  int bits;
  HashFunction hf;
  int *tab;
  bool TryFill(const vector<int> &);
};

SimplePerfectHashSet::SimplePerfectHashSet(const vector<int> &v) {
  bits = 1;
  int minsize = 2*size(v)*size(v);
  while((1<<bits)<minsize) bits++;
  tab = new int[1<<bits];
  while(!TryFill(v)) {
  }
}

bool SimplePerfectHashSet::TryFill(const vector<int> &v) {
  int sz = 1<<bits;
  REP(i,sz) tab[i]=-1;
  hf = RandomHashFunction(bits);
  for(int x : v) {
    unsigned h = hf.Apply(x);
    if(tab[h]!=-1) return false;
    tab[h] = x;
  }
  return true;
}

inline bool SimplePerfectHashSet::Contains(int x) const {
  unsigned h = hf.Apply(x);
  return tab[h] == x;
}

class PerfectHashSet {
 public:
  explicit PerfectHashSet(const vector<int> &v);
  inline bool Contains(int) const;
 private:
  int bits;
  HashFunction hf;
  SimplePerfectHashSet **tab;
};

PerfectHashSet::PerfectHashSet(const vector<int> &v) {
  bits = 1;
  while((1<<bits) < size(v)) ++bits;
  int n = 1<<bits;
  tab = new SimplePerfectHashSet*[n];
  vector<vector<int>> v2;
  for(;;) {
    v2.clear(); v2.resize(n);
    hf = RandomHashFunction(bits);
    for(int x : v) {
      unsigned h = hf.Apply(x);
      v2[h].push_back(x);
    }
    int sum=0;
    for(const vector<int> &v3 : v2) sum += size(v3)*size(v3);
    if(sum <= 6*size(v)) break;
  }
  REP(i,n) {
    if(v2[i].empty()) tab[i]=nullptr;
    else tab[i]=new SimplePerfectHashSet(v2[i]);
  }
}

inline bool PerfectHashSet::Contains(int x) const {
  unsigned h = hf.Apply(x);
  return tab[h] && tab[h]->Contains(x);
}

int gNumberOfNodes;
int gMyNodeId;
int gActiveNodes;

int N;
vector<int> gQueries;
vector<pair<int,int>> gQueryPairs;  // index into gQueries
vector<int> gAnswers;  // only node 0

int IndexOfQuery(int q) {
  auto it = lower_bound(gQueries.begin(), gQueries.end(), q);
  if(it==gQueries.end() || *it != q) return -1;
  return it - gQueries.begin();
}

void Initialize() {
  ios_base::sync_with_stdio(false); cin.tie(nullptr);
  gNumberOfNodes = NumberOfNodes();
  gMyNodeId = MyNodeId();
  N = NumberOfStudents();
  int nqueries = NumberOfQueries();
  gQueries.reserve(2*nqueries);
  gQueryPairs.reserve(nqueries);
  REP(i,nqueries) {
    pair<int,int> p;
    p.first = QueryFrom(i+1) - 1;
    p.second = QueryTo(i+1) - 1;
    gQueries.push_back(p.first);
    gQueries.push_back(p.second);
    gQueryPairs.push_back(p);
  }
  sort(gQueries.begin(), gQueries.end());
  gQueries.erase(unique(gQueries.begin(), gQueries.end()), gQueries.end());
  for(auto &p : gQueryPairs) {
    p.first = IndexOfQuery(p.first);
    p.second = IndexOfQuery(p.second);
  }
}

void PickActiveNodes() {
  if(N <= SINGLE_NODE_THRESHOLD) gActiveNodes = 1;
  else gActiveNodes = min(gNumberOfNodes, N / MINIMUM_PER_NODE);
  if(gActiveNodes < MIN_TEAM) gActiveNodes = 1;
}

int EitherNeighbor(int x, int dir=0) {
  if(dir==0) {
    return FirstNeighbor(x+1)-1;
  } else {
    return SecondNeighbor(x+1)-1;
  }
}

int gPredictionReverse = 0;
unsigned gBadPredictionHistory = 0;
int gBadPredictionCount = 0;

int Predict(int prev) {
  int dir = 2*prev<N ? 1 : 0; // small prev -> go up
  return dir ^ gPredictionReverse;
}

void PredictionFeedback(bool success) {
  gBadPredictionCount -= gBadPredictionHistory & 1;
  if(!success) {
    gBadPredictionHistory |= 1u << PREDICTION_HISTORY;
    ++gBadPredictionCount;
    if(gBadPredictionCount >= PREDICTION_FLIP) {
      gPredictionReverse ^= 1;
      gBadPredictionCount = 0;
      gBadPredictionHistory = 0;
    }
  }
  gBadPredictionHistory >>= 1;
}

int OtherNeighbor(int x, int prev) {
  int dir = Predict(prev);  // 0 = down, 1 = up
  int res;
  if(dir==0) {
    res = FirstNeighbor(x+1)-1;
    bool success = (res!=prev);
    PredictionFeedback(success);
    if(!success) res = SecondNeighbor(x+1)-1;
  } else {
    res = SecondNeighbor(x+1)-1;
    bool success = (res!=prev);
    PredictionFeedback(success);
    if(!success) res = FirstNeighbor(x+1)-1;
  }
  return res;
}

struct Path {
  int len;
  int v[2]; // index into samples
  vector<pair<int,int>> found;  // query index, position
  bool Redundant() const {
    return v[0] > v[1];
  }
};

struct TwoPaths {
  int n;
  Path *p[2];
  TwoPaths():n(0), p{nullptr,nullptr} {}
  void Add(Path *q) { p[n++] = q; }
};

PerfectHashSet *gPHS;
vector<int> gSamples;
vector<pair<int,int>> gSortedSamples;
vector<TwoPaths> gPaths;

int IndexOfSample(int x) {
  auto it = lower_bound(gSortedSamples.begin(), gSortedSamples.end(), make_pair(x,0));
  assert(it != gSortedSamples.end() && it->first==x);
  return it->second;
}

void GenerateSamples() {
  set<int> seen(gQueries.begin(), gQueries.end());
  int need = gActiveNodes * SAMPLES_PER_NODE;
  gSamples.reserve(need);
  while(size(gSamples) < need) {
    int x = Random(N);
    if(!seen.count(x)) {
      gSamples.push_back(x);
      seen.insert(x);
    }
  }
  gSortedSamples.reserve(need);
  REP(i,need) gSortedSamples.emplace_back(gSamples[i], i);
  sort(gSortedSamples.begin(), gSortedSamples.end());
}

void CreatePHS() {
  vector<int> v = gSamples;
  v.insert(v.end(), gQueries.begin(), gQueries.end());
  gPHS = new PerfectHashSet(v);
}

void LonelySolution() {
  gAnswers.assign(size(gQueries), -1);
  CreatePHS();
  int prev = -1;
  int cur = 0;
  REP(index, N) {
    if(gPHS->Contains(cur)) {
      int idx = IndexOfQuery(cur);
      assert(idx != -1);
      gAnswers[idx] = index;
    }
    int next = prev==-1 ? EitherNeighbor(cur) : OtherNeighbor(cur, prev);
    prev = cur;
    cur = next;
  }
  assert(cur == 0);
}

void AddPath(Path *p) {
  REP(i,2) gPaths[p->v[i]].Add(p);
}

void SendPath(Path *p) {
  PutInt(0, p->len);
  REP(i,2) PutInt(0, p->v[i]);
  PutInt(0, size(p->found));
  for(const auto &x : p->found) {
    PutInt(0, x.first);
    PutInt(0, x.second);
  }
}

void FinishSending() {
  PutInt(0, -1);
  Send(0);
}

Path *ReceivePath(int node) {
  int len = GetInt(node);
  if(len<0) return nullptr;
  Path *p = new Path;
  p->len = len;
  REP(i,2) p->v[i] = GetInt(node);
  int nfound = GetInt(node);
  p->found.reserve(nfound);
  REP(i, nfound) {
    pair<int,int> x;
    x.first = GetInt(node);
    x.second = GetInt(node);
    p->found.push_back(x);
  }
  return p;
}

Path *TracePath(int start, int dir) {
  Path *p = new Path();
  p->len = 1;
  p->v[0] = start;
  int prev = gSamples[start];
  int cur = EitherNeighbor(prev, dir);
  for(;;) {
    if(gPHS->Contains(cur)) {
      int idx = IndexOfQuery(cur);
      if(idx==-1) break; // found another sample
      p->found.emplace_back(idx, p->len);
    }
    int next = OtherNeighbor(cur, prev);
    prev = cur; cur = next;
    ++p->len;
  }
  p->v[1] = IndexOfSample(cur);
  return p;
}

void TracePaths() {
  for(int i=SAMPLES_PER_NODE * gMyNodeId; i < SAMPLES_PER_NODE * (gMyNodeId+1); ++i) {
    REP(dir,2) {
      Path *p = TracePath(i, dir);
      if(p->Redundant()) { delete p; continue; }
      if(gMyNodeId==0) {
        AddPath(p);
      } else {
        SendPath(p);
        delete p;
      }
    }
  }
}

void ReceiveOtherPaths() {
  for(int node=1;node<gActiveNodes;++node) {
    Receive(node);
    for(;;) {
      Path *p = ReceivePath(node);
      if(!p) break;
      AddPath(p);
    }
  }
}

void BuildAnswer() {
  gAnswers.assign(size(gQueries), -1);
  int dist = 0;
  Path *prev = nullptr;
  int cur = 0;
  while(dist < N) {
    assert(gPaths[cur].n==2);
    Path *p = gPaths[cur].p[0];
    if(p==prev) p = gPaths[cur].p[1];
    prev = p;
    if(cur==p->v[0]) {
      for(const auto &x : p->found) {
        gAnswers[x.first] = dist + x.second;
      }
      cur = p->v[1];
      dist += p->len;
    } else {
      assert(cur==p->v[1]);
      cur = p->v[0];
      dist += p->len;
      for(const auto &x : p->found) {
        gAnswers[x.first] = dist - x.second;
      }
    }
  }
  assert(dist==N);
}

void TeamSolution() {
  gAnswers.assign(size(gQueries), 0);
  GenerateSamples();
  CreatePHS();
  if(gMyNodeId==0) {
    gPaths.resize(size(gSamples));
  }
  TracePaths();
  if (gMyNodeId==0) {
    ReceiveOtherPaths();
    BuildAnswer();
  } else {
    FinishSending();
  }
}

void PrintAnswer() {
  for(const auto &p : gQueryPairs) {
    int a = gAnswers[p.first];
    int b = gAnswers[p.second];
    int res = abs(a-b);
    res = min(res, N-res);
    cout << res << '\n';
  }
}

}  // namespace

int main() {
  Initialize();
  PickActiveNodes();
  if(gMyNodeId >= gActiveNodes) return 0;
  if(gActiveNodes == 1) {
    LonelySolution();
  } else {
    TeamSolution();
  }
  if (gMyNodeId == 0) {
    PrintAnswer();
  }
}