Cod sursa(job #401694)

Utilizator hungntnktpHungntnktp hungntnktp Data 23 februarie 2010 04:11:18
Problema Gropi Scor 100
Compilator fpc Status done
Runda Arhiva de probleme Marime 2.41 kb
const fi  = 'gropi.in';
      fo  = 'gropi.out';
      maxn  = 111111;
var ax,ay  :  array[0..maxn] of longint;
    s      :  array[0..maxn] of longint;
    d1,d2  : longint;
    n,m,t,test,c : longint;
    sx,sy,fx,fy : longint;
    f1,f2 : text;

procedure init;
var i,j,x,y : longint;
 begin
  readln(f1,c,n);
  for i := 1 to n do
   begin
    readln(f1,ax[i],ay[i]);
   end;
 end;

procedure sort(lo,hi:longint);
var tg,i,j,x,y : longint;
 begin
  i := lo; j := hi; x := ay[(i+j) div 2];
  repeat
   while ay[i] < x do inc(i);
   while ay[j] > x do dec(j);
   if i <= j then
    begin
     tg := ay[i]; ay[i] := ay[j]; ay[j] := tg;
     tg := ax[i]; ax[i] := ax[j]; ax[j] := tg;
     inc(i); dec(j);
    end;
  until i > j;
  if i < hi then sort(i,hi);
  if j > lo then sort(lo,j);
 end;

procedure cbi;
var i : longint;
 begin
  for i := 2 to n do
   s[i] := s[i-1] + abs(ax[i] - ax[i-1]) + abs(ay[i] - ay[i-1]);
 end;

procedure findnext(a:longint;var x : longint);
var mid,dau,cuoi : longint;
 begin
  dau := 1; cuoi := n;
  while cuoi - dau > 1 do
   begin
    mid := (dau+cuoi) div 2;
    if ay[mid] <= a then dau := mid else cuoi := mid;
   end;
  if ay[dau] >= a then x := dau else x := cuoi;
 end;

procedure findprev(a:longint;var x : longint);
var mid,dau,cuoi : longint;
 begin
  dau := 1; cuoi := n;
  while cuoi - dau > 1 do
   begin
    mid := (dau+cuoi) div 2;
    if ay[mid] <= a then dau := mid else cuoi := mid;
   end;
  if ay[cuoi] <= a then x := cuoi else x := dau;
 end;

procedure xuly;
var i,j,x1,y1,x2,y2,tg,res : longint;
 begin
  res := 0;
  if sy > fy then
   begin
    tg := sx; sx := fx; fx := tg;
    tg := sy; sy := fy; fy := tg;
   end;
  if (fy < ay[1]) or (sy > ay[n]) then
   begin
    Writeln(f2,abs(fy - sy) + abs(fx - sx) + 1);
    exit;
   end;
  if sy = fy then
   begin
    Writeln(f2,abs(sx-fx) + 1);
    exit;
   end;
  findnext(sy,i);
  findprev(fy,j);
  if j < i then
   begin
    Writeln(f2,abs(fy - sy) + abs(fx - sx) + 1);
    exit;
   end;
  res := abs(3 - ax[i]-sx) + abs(ay[i] - sy);
  res := res + s[j] - s[i];
  res := res + abs(fx - 3 + ax[j]) + abs(fy -ay[j]);
  Writeln(f2,res + 1);
 end;

begin
 assign(f1,fi); reset(f1);
 assign(f2,fo); rewrite(f2);
 init;
 sort(1,n);
 cbi;
 readln(f1,test);
 for t := 1 to test do
  begin
   readln(f1,sx,sy,fx,fy);
   xuly;
  end;
 close(f1); close(f2);
end.