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
// Krzysztof Baranski

#include "kollib.h"
#include "message.h"
#include <cstdio>
#include <vector>
//#include <queue>
using namespace std;

#define ABS(a) ((a)<0?-(a):(a))
#define MIN(a,b) ((a)<(b)?(a):(b))


/*
queue<int> QQQ[20];
int mynode;
int insta=5;
int MyNodeId() {return mynode;}
int NumberOfNodes() {return insta;}
void PutInt(int i,int j) {printf("  zaladowalem do %d wartosc %d\n",i,j);QQQ[mynode].push(j);}
void Send(int i) {printf("  wyslalem do %d\n",i);}
int GetInt(int i){printf("  zwracam %d z instancji %d\n",QQQ[i].front(),i);int res=QQQ[i].front();QQQ[i].pop();return res;}
void Receive(int i){}*/

int main() {
	//for(mynode=insta-1;mynode>=0;--mynode) {
	//printf(">>> JESTEM W INSTANCJI: %d\n",mynode);
	
	register int students = NumberOfStudents()-1;
	register int nodes = NumberOfNodes()-1;
	register int id = MyNodeId()-1;
	register int queries = NumberOfQueries();
	
	if(MyNodeId() != 0) {
		
		
		
		vector<int> odleglosci(students/nodes+1);
		
		
		register int curr = FirstNeighbor(1);
		register int prev = 1;
		
		register int dist = 1;
		
		while(curr!=1) {
			register int child = curr-2;
			
			if(child%nodes==id) {
				odleglosci[child/nodes]=(dist<=students-dist+1 ? dist : dist-students-1);
			}
			
			curr=(FirstNeighbor(curr)==prev?SecondNeighbor((prev=curr)):FirstNeighbor((prev=curr)));
			++dist;
		}
		
		//for(int i=0;i<odleglosci.size();++i) printf("%d ",odleglosci[i]);
		//printf("\n");
		
		for(register int i = 1; i <= queries; ++i) {
			//printf("  > zapytanie %d\n",i);
			
			register int from = QueryFrom(i);
			register int to = QueryTo(i);
			
			if(from!=1 && (from-2)%nodes==id && from!=to) {
				PutInt(0,odleglosci[(from-2)/nodes]);
				Send(0);
			}
			
			if(to!=1 && (to-2)%nodes==id && from!=to) {
				PutInt(0,odleglosci[(to-2)/nodes]);
				Send(0);
			}
		}
		
		
	} else {
		
		for(register int i = 1; i <= queries; ++i) {
			register int from = QueryFrom(i);
			register int to = QueryTo(i);
			
			register int dist = 0;
			
			if(from!=to) {
				register int lewa = 0;
				if(from!=1) {
					register int odb = (from-2)%nodes+1;
					Receive(odb);
					lewa = GetInt(odb);
				}
				
				register int prawa = 0;
				if(to!=1) {
					register int odb = (to-2)%nodes+1;
					Receive(odb);
					prawa = GetInt(odb);
				}
				
				dist = ABS(lewa-prawa);
				dist = MIN(dist,students-dist+1);
			} 
			
			
			printf("%d\n",dist);
		}
		
	}
	
//}
	return 0;
}