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
#include "kollib.h"
#include "message.h"
#include <cstdio>
#include <set>
#include <map>
using namespace std;
void walk(int &f,int &ff){int nf=(FirstNeighbor(f)==ff)?SecondNeighbor(f):FirstNeighbor(f);ff=f;f=nf;}
void walk(int &f,int &ff,int k){for(int i=0;i<k;++i)walk(f,ff);}
typedef set<int> S;typedef map<int,int> M;
void master(){
    int s=MyNodeId(),n=NumberOfNodes(),k=NumberOfStudents(),m=NumberOfQueries();
    M v;
    for(int i=0;i<n;++i){
        s=Receive(-1);int e=GetInt(s);
        for(int j=0;j<e;++j){int q=GetInt(s);v[q]=GetInt(s);}
    }
    for(int i=0;i<m;++i){
        int d=v[QueryFrom(i+1)]-v[QueryTo(i+1)];if(d<0)d=-d;if(k-d<d)d=k-d;
        printf("%d\n",d);
    }
}
void client(){
    S u;M v;
    int s=MyNodeId(),n=NumberOfNodes(),k=NumberOfStudents(),m=NumberOfQueries(),o=n-1,f=1,ff=FirstNeighbor(1);
    walk(f,ff,s);
    for(int i=0;i<m;++i){u.insert(QueryFrom(i+1));u.insert(QueryTo(i+1));}
    int steps=1+k/n,pos=s;
    for(int i=0;i<steps;++i){if(u.find(f)!=u.end())v[f]=pos%k;walk(f,ff,n);pos+=n;}
    PutInt(o,(int)v.size());for(M::iterator i=v.begin();i!=v.end();++i){PutInt(o,i->first);PutInt(o,i->second);}
    Send(o);
}
int main(){
    client();
    if(MyNodeId()==NumberOfNodes()-1)master();
    return 0;
}