#include <stdio.h>
#include <string.h>
#include <stdlib.h>
FILE *in, *out;
long nrColC;
long gr;
char line[1000];
int gropi[3][2000000];
long nrTras;
long xPl;
long yPl;
long xDst;
long yDst;
int directie;
int solutie = 0;
struct arb
{
long x;
long y;
struct arb * hor;
struct arb * ver;
struct arb * tt;
} plecare;
void parcurgere(struct arb *nod)
{
long yNext;
long xNext;
long counter=1;
struct arb * aux2, *aux1, *aux_af;
if (solutie) {
return;
}
if (nod->y==0 || nod->y>nrColC) {
// printf ("nod->y = %ld , nrColC = nrColC\n" , nod->y,nrColC) ;
return;//nu e solutie, se duce ca un bou
}
int ver = ((nod->y)-yDst)*directie;
if (ver>0) {
// printf ("((nod->y-yDst)*directie) = %ld\n", ver);
return;//a luat-o rara
}
if (nod->x==xDst && nod->y ==yDst) {
// printf ("\n\n\nsolutie\n\n\n");
//solutie
for (aux_af=nod; aux_af!=&plecare;aux_af=aux_af->tt) {
// printf ("x=%ld , y=%ld\n", aux_af->x, aux_af->y);
++counter;
}
// printf("counter = %ld\n", counter);
fprintf(out,"%ld\n", counter);
solutie = 1;
return;
}
// printf ("nod->x = %ld , nod->y = %ld\n", nod->x, nod->y);
yNext = nod->y+directie;
if(gropi[nod->x][yNext]==0) {
//hai si pe aici
aux1 = (struct arb*)malloc(sizeof(struct arb));
aux1->tt = nod;
aux1->x = nod->x;
aux1->y = yNext;
nod->hor = aux1;
// parcurgere(aux);
parcurgere(nod->hor);
}
if (nod->x==1) xNext =2;
else xNext =1;
if (gropi[xNext][nod->y]==0) {
//hai si pe aici
aux2 = (struct arb*)malloc(sizeof(struct arb));
aux2->tt = nod;
aux2->x = xNext;
aux2->y = nod->y;
nod->ver = aux2;
// parcurgere(aux);
parcurgere(nod->ver);
}
}
int main()
{
unsigned long x,y;
in = fopen("gropi.in","r");
out =fopen("gropi.out","w");
fscanf(in, "%ld %ld", &nrColC, &gr);
unsigned long int i=0;
memset(gropi, 0, 6000000);
// printf("%ld %ld\n", nrColC, gr);
for (;i<gr;++i) {
fscanf(in, "%ld %ld",&x, &y);
gropi[x][y]=1;
// printf("__ %ld %ld %d \n",x, y, gropi[x][y]/*, gropi[y][y]*/);
}
fscanf (in, "%ld", &nrTras);
// printf ("nrTras = %ld\n", nrTras);
for (i=0;i<nrTras;++i) {
solutie = 0;
fscanf (in, "%ld %ld %ld %ld", &xPl, &yPl, &xDst, &yDst);
// printf("%ld %ld %ld %ld\n", xPl, yPl, xDst, yDst);
plecare.x = xPl;
plecare.y = yPl;
// printf ("plecare.x = %ld , plecare.y = %ld\n", plecare.x, plecare.y);
if (yPl==yDst) {
//solutie
fprintf(out,"0\n");
}
else {
if (yPl<yDst) directie = 1;
else directie = -1;
parcurgere(&plecare);
}
}
fclose(in);
fclose(out);
return 0;
}