Cod sursa(job #197622)

Utilizator radu_voroneanuVoroneanu Radu Stefan radu_voroneanu Data 5 iulie 2008 12:19:04
Problema Gropi Scor 0
Compilator fpc Status done
Runda Junior Challenge 2008 Marime 2.37 kb
type list=array[0..100000] of longint;

var v1,v2,v3,part:list;
    f,g:text;
    aux,poz2,y1,rez,y2,m,poz1,x,y,x1,x2,c,n,i:longint;

function caut(x,st,dr:longint):longint;
 var mij:longint;
 begin
  if st>dr then caut:=0
  else begin
   mij:=(st+dr) shr 1;
   if v3[mij]>x then begin
    if v3[mij-1]<=x then
     caut:=mij
    else
     caut:=caut(x,st,mij-1);
   end
   else
    caut:=caut(x,mij+1,dr);
  end;
 end;

procedure QSort(var A: List);
 var Lo,Hi:longint;

 procedure Sort(l, r: longint);
 var
   i, j, x, y: longint;
 begin
   i := l; j := r; x := a[(l+r) DIV 2];
   repeat
     while a[i] < x do i := i + 1;
     while x < a[j] do j := j - 1;
     if i <= j then
     begin
       y := a[i]; a[i] := a[j]; a[j] := y;
       i := i + 1; j := j - 1;
     end;
   until i > j;
   if l < j then Sort(l, j);
   if i < r then Sort(i, r);
 end;

 begin {QuickSort};
   lo:=1;
   hi:=a[0];
   Sort(Lo,Hi);
 end;

begin
 assign(f,'gropi.in'); reset(f);
 assign(g,'gropi.out'); rewrite(g);
 read(f,c,n);
 for i:=1 to n do begin
  read(f,x,y);
  case x of
  1: begin
        inc(v1[0]);
        v1[v1[0]]:=y;
  end;
  2: begin
        inc(v2[0]);
        v2[v2[0]]:=y;
  end;
  end;
 end;
 inc(v2[0]);
 v2[v2[0]]:=c+1;
 inc(v1[0]);
 v1[v1[0]]:=c+1;
 qsort(v1);
 qsort(v2);
 x1:=1;
 x2:=1;
 v3[1]:=0;
 v3[0]:=2;
 if v1[x1]<v2[x2] then begin
  v3[2]:=v1[x1];
  part[2]:=1;
  inc(x1);
 end
 else begin
  v3[2]:=v2[x2];
  part[2]:=2;
  inc(x2);
 end;
 while (x1<v1[0]) and (x2<v2[0]) do begin
  inc(v3[0]);
  part[v3[0]]:=3-part[v3[0]-1];
  case part[v3[0]] of
  1: begin
        while (x1<v1[0]) and (v1[x1]<v3[v3[0]-1]) do
         inc(x1);
        v3[v3[0]]:=v1[x1];
  end;
  2: begin
        while (x2<v1[0]) and (v2[x2]<v3[v3[0]-1]) do
         inc(x2);
        v3[v3[0]]:=v2[x2];
  end;
  end;
 end;
 read(f,m);
 n:=v3[0];
 for i:=1 to m do begin
  read(f,x1,y1,x2,y2);
  if y1>y2 then begin
   aux:=y1;
   y1:=y2;
   y2:=aux;
   aux:=x1;
   x1:=x2;
   x2:=aux;
  end;
  poz1:=caut(y1,2,n);
  poz2:=caut(y2,2,n);
  if (poz1=2) and (part[2]<>x1) then
   inc(poz1);
  if (poz2=2) and (part[2]<>x2) then
   inc(poz2);
  rez:=poz2-poz1;
  if (x1<>part[poz1]) then
   inc(rez);
  if (x2<>part[poz2]) then
   inc(rez);
  rez:=rez+(y2-y1+1);
  writeln(g,rez);
 end;
 close(f); close(g);
end.