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

#include "message.h"
#include "kollib.h"

int go(int A, int from, int prev)
{
	int counter = 1;
	while (from != A)
	{
		int p = FirstNeighbor(from);

		if (p == prev)
			p = SecondNeighbor(from);

		prev = from;
		from = p;

		counter++;
	}

	return counter;
}

int N, ID, M, Q;
void master()
{
	int k = 1;
	int ans = 0;
	int answers[Q];

	for (int i=0; i<Q; i++)
	{
		int f, t;
		f = QueryFrom(i+1);
		t = QueryTo(i+1);

		answers[i] = -1;

		PutInt(k, f);
		PutInt(k, t);
		PutInt(k, 0);
		PutInt(k, i);
		Send(k);
		k++; if (k == N) k = 1;
	
		PutInt(k, f);
		PutInt(k, t);
		PutInt(k, 1);
		PutInt(k, i);
		Send(k);
		k++; if (k == N) k = 1;
	}

	while (ans < Q*2)
	{
		int from = Receive(-1);

		int a = GetInt(from);
		int v = GetInt(from);

//		fprintf(stderr, "answer for %i is %i\n", a, v);

		if (answers[a] == -1 || answers[a] > v)
			answers[a] = v;
		ans++;
	}

	for (int i=0; i<Q; i++)
		printf("%i\n", answers[i]);
}

void answer(int q, int v)
{
	PutInt(0, q);
	PutInt(0, v);
	Send(0);
}
void slave()
{
	Receive(0);

	int f = GetInt(0);
	int t = GetInt(0);
	int m = GetInt(0);
	int q = GetInt(0);

	if (f == t)
	{
		answer(q, 0);
		return;
	}

	int a;

	if (m == 0)
	{
		a = go(t, FirstNeighbor(f), f);
	}
	else
	{
		a = go(t, SecondNeighbor(f), f);
	}

	answer(q, a);
}

int main()
{
	N = NumberOfNodes();
	ID = MyNodeId();
	M = NumberOfStudents();
	Q = NumberOfQueries();
	int run = ID-1;

	if (ID == 0)
	{
		master();
	}
	else
	{
		while (run < Q*2)
		{
			slave();
			run += (N-1);
		}
	}
}