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

#include <algorithm>
#include <map>
#include <random>
#include <set>
#include <vector>
#include <unordered_map>

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

int numThreads;
int numStudents;

static const char MSG_FOUND_STUDENT_BASE = 42;
static const char MSG_FOUND_PIVOT_BASE = 69;
inline constexpr char msgFoundStudent(int run) { return MSG_FOUND_STUDENT_BASE + run; }
inline constexpr char msgFoundPivot(int run) { return MSG_FOUND_PIVOT_BASE + run; }

// bool vocalizeSlaves = false;
// bool vocalizeMaster = false;

struct connection
{
	int to;
	int length;
	int alignment;
};

void generatePivots(std::set<int> & pivots)
{
	pivots.clear();
	pivots.insert(-7);	//Zerowy element jest dla wyrównania
	
	if (numStudents / numThreads > 2)
	{
		std::ranlux48 randEngine;
		randEngine.seed((numThreads - 69) ^ (numStudents + 42));
		std::uniform_int_distribution<int> distribution(1, numStudents);
		
		for (int i = 1; i < numThreads; i++)
		{
			int nextPivot = distribution(randEngine);
			while (pivots.find(nextPivot) != pivots.end())
				nextPivot = distribution(randEngine);
			
			pivots.insert(nextPivot);
			//printf("(%i)\n", nextPivot);
		}
	}
	else
	{
		for (int i = 1; i < numThreads; i++)
			pivots.insert(i);
	}
}

void slave()
{
	if (MyNodeId() > numStudents)
		return;	//Nie potrzebujemy aż tylu węzłów
	
	// if (vocalizeSlaves)
	// 	fprintf(stdout, "Slave #%d gained conciousness\n", MyNodeId());
	
	//Wszyscy generują zbiór punktów, z których startują slave'y
	std::set<int> pivotsSet;
	generatePivots(pivotsSet);
	
	// if (vocalizeSlaves)
	// 	printf("Slave #%d has generated his pivots.\n", MyNodeId());
	
	//Przepisujemy, dla szybkości, do vectora
	std::vector<int> pivots;
	pivots.reserve(pivotsSet.size());
	for (int i : pivotsSet)
		pivots.push_back(i);
	
	//Wczytajmy zbiór studentów których mamy szukać
	std::vector<int> studentsToFind;
	int nq = NumberOfQueries();
	studentsToFind.reserve(2 * nq);
	for (int i = 1; i <= nq; i++)
	{
		studentsToFind.push_back(QueryFrom(i));
		studentsToFind.push_back(QueryTo(i));
	}
	
	std::sort(studentsToFind.begin(), studentsToFind.end());
	
	for (int run : { 0, 1 })
	{
		int tail = pivots[MyNodeId()];
		int head = (run == 0) ? FirstNeighbor(tail) : SecondNeighbor(tail);
		int dist = 1;
		
		//if (vocalizeSlaves)
		//	printf("Slave Run %d %d %d\n", run, tail, head);
		
		while (!std::binary_search(pivots.begin(), pivots.end(), head))
		{
			if (std::binary_search(studentsToFind.begin(), studentsToFind.end(), head))
			{
				//Raportujemy o znalezionym studencie masterowi
				PutChar(0, msgFoundStudent(run));
				PutInt(0, head);
				PutInt(0, dist);
				Send(0);
			}
			
			int next = FirstNeighbor(head);
			if (next == tail)
				next = SecondNeighbor(head);
			
			//if (next == -7)
			//	printf("Oooops??! (%d -> %d)\n", head, next);
			
			//if (vocalizeSlaves)
			//	printf("Go %d -> %d\n", head, next);
			
			tail = head;
			head = next;
			dist++;
		}
		
		//Raportujemy o napotkaniu pivota masterowi
		PutChar(0, msgFoundPivot(run));
		PutInt(0, head);
		PutInt(0, dist);
		Send(0);
	}
	
	//Koniec roboty slave'a
	//if (vocalizeSlaves)
	//	fprintf(stdout, "Slave #%d has fulfilled his job.\n", MyNodeId());
}

void master()
{
	//Wszyscy generują zbiór punktów, z których startują slave'y
	std::set<int> pivotsSet;
	generatePivots(pivotsSet);
	
	//if (vocalizeMaster)
		// fprintf(stdout, "Master has generated his pivots.\n");
	
	//Potrzebujemy indeksowanego wyszukiwania pivota, więc potrzebne jest to
	std::vector<int> pivots;
	pivots.reserve(pivotsSet.size());
	for (int i : pivotsSet)
		pivots.push_back(i);
	
	//if (vocalizeMaster)
	//{
	//	printf("Pivots:\n");
	//	for (int i : pivots)
	//		printf("%i\n", i);
	//}
	
	//Budujemy strukturę na odległości do studentów
	std::unordered_multimap<int, connection> pivotConns;
	std::unordered_multimap<int, connection> pivotToStudentConns;
	
	//Message loop
	// if (vocalizeMaster)
	// 	fprintf(stdout, "Master has begun receiving messages.\n");
	int remainingTasks = 2 * (numThreads - 1);
	while (remainingTasks != 0)
	{
		int sender = Receive(-1);
		char msgType = GetChar(sender);
		int msgTarget = GetInt(sender);
		int msgDistance = GetInt(sender);
		
		switch (msgType)
		{
			case msgFoundStudent(0):
			case msgFoundStudent(1):
			{
				connection conn;
				conn.to = msgTarget;
				conn.length = msgDistance;
				conn.alignment = msgType - MSG_FOUND_STUDENT_BASE;
				
				pivotToStudentConns.insert(std::pair<int, connection>(pivots[sender], conn));
				// if (vocalizeMaster)
				 	// printf("Master inserted found student. (%d -> %d)\n", pivots[sender], conn.to);
			}
			break;
			
			case msgFoundPivot(0):
			case msgFoundPivot(1):
			{
				connection conn;
				conn.to = msgTarget;
				conn.length = msgDistance;
				conn.alignment = msgType - MSG_FOUND_PIVOT_BASE;
				
				pivotConns.insert(std::pair<int, connection>(pivots[sender], conn));
				// if (vocalizeMaster)
				 	// printf("Master reports slave #%d had found a pivot. (%d -> %d)\n", sender, pivots[sender], conn.to);
				
				remainingTasks--;
			}
			break;
		}
	}
	
	// if (vocalizeMaster)
	 	// fprintf(stdout, "Master completed his mailing task.\n");
	
	std::map<int, int> studentPrefSum;
	
	// printf("%i\n", pivots.size());
	// for (auto it : pivotConns)
	// 	printf("%i => %i\n", it.first, it.second.to);
	
	//printf("%d\n", pivots[1]);
	
	int firstPivot = pivots[1];
	int head = firstPivot;
	int tail = pivotConns.find(firstPivot)->second.to;
	
	int dist = 0;
	
	// printf("Now, Master is speaking!\n");
	
	// printf("%d %d\n", pivots.size(), pivotConns.size());
	
	do
	{
		auto itpair = pivotConns.equal_range(head);
		int next = -1;
		int diffDist;
		int forwardAlignment;
		
		studentPrefSum[head] = dist;
		
		for (auto it = itpair.first; it != itpair.second; it++)
		{
			if (it->second.to != tail)
			{
				next = it->second.to;
				diffDist = it->second.length;
				forwardAlignment = it->second.alignment;
				break;
			}
		}
		
		auto itpair2 = pivotToStudentConns.equal_range(head);
		for (auto it = itpair2.first; it != itpair2.second; it++)
		{
			if (it->second.alignment == forwardAlignment)
				studentPrefSum.insert(std::pair<int, int>(it->second.to, dist + it->second.length));
		}
		
		//if (next != head)
		//	printf("At %d\n", head);
		
		tail = head;
		head = next;
		dist += diffDist;
		
	}	while (head != firstPivot);
	
	//printf("I made it!\n");
	
	int nq = NumberOfQueries();
	for (int i = 1; i <= nq; i++)
	{
		int from = QueryFrom(i);
		int to = QueryTo(i);
		
		if (from == to)
		{
			//printf("%d is the same...\n", i);
			puts("0");
			continue;
		}
		
		int prefDist = std::abs(studentPrefSum[from] - studentPrefSum[to]);
		//printf("(%d %d)\n", studentPrefSum[from], studentPrefSum[to]);
		//printf("[%d %d]\n", from, to);
		int realDist = std::min(prefDist, numStudents - prefDist);
		printf("%d\n", realDist);
	}
	
	// if (vocalizeMaster)
	// 	printf("Master has completed his duty.\n");
}

int main()
{
	// printf("Hey!\n");
	
	// int k;
	// if (scanf("%d", &k))
	// {
	// 	if (k == 0)
	// 		vocalizeMaster = true;
	// 	if (k == 1)
	// 		vocalizeSlaves = true;
	// }
	
	numStudents = NumberOfStudents();
	numThreads = std::min(numStudents + 1, NumberOfNodes());
	
	if (NumberOfQueries() == 0)
		return 0;
	
	if (MyNodeId() == 0)
		master();
	else
		slave();
	
	return 0;
}