Cod sursa(job #197692)

Utilizator tamas_iuliaTamas Iulia tamas_iulia Data 5 iulie 2008 13:57:15
Problema Gropi Scor 50
Compilator fpc Status done
Runda Junior Challenge 2008 Marime 1.89 kb
var gropi: array[1..2,0..100010] of longint;
    i,j,n,p,m,c,aux,sum,a,b,xi,yi,xf,yf : longint;
    nrg : array[1..2] of longint;
    f,g : text;
    gasit : boolean;

procedure sort(l,r,z : longint);
var i,j,x,aux : longint;
begin
     i:=l; j:=r; x:=gropi[z,(l+r)div 2];
     repeat
           while (gropi[z,i]<x) do inc(i);
           while (x<gropi[z,j]) do dec(j);
           if i<=j then
           begin
                aux:=gropi[z,i];gropi[z,i]:=gropi[z,j];gropi[z,j]:=aux;
                inc(i); dec(j);
           end;
     until i>j;
     if l<j then sort(l,j,z);
     if i<r then sort(i,r,z);
end;

function caut_bin(l,r,z,val : longint):longint;
var m,ok : longint;
begin
  ok:=-1;
  while l<=r do
  begin
    m:=(l+r)div 2;
      if gropi[z,m]>=val then
      begin
        ok:=gropi[z,m];
        r:=m-1;
      end
      else l:=m+1;
  end;
  caut_bin:=ok;
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,a,b);
      inc(nrg[a]);
      gropi[a,nrg[a]]:=b;
    end;
  sort(1,nrg[1],1);
  sort(1,nrg[2],2);
  read(f,m);
    for i:=1 to m do
    Begin
      read(f,xi,yi,xf,yf);
        if (yi>yf)or((yi=yf)and(xi>xf))then
        begin
          aux:=xi;xi:=xf;xf:=aux;
          aux:=yi;yi:=yf;yf:=aux;
        end;

      sum:=1; gasit:=false;
      repeat
        p:=caut_bin(1,nrg[xi],xi,yi);
          if (p=-1)or(p>yf) then
          begin
            sum:=sum+yf-yi;
              if xi<>xf then inc(sum);
            gasit:=true;
          end
          else
          begin
            dec(p);
            sum:=sum+p-yi+1; { + inca 1 pt ca se ridica sau coboara}
              if xi=1 then xi:=2 else xi:=1;
              yi:=p;
          end;
      until gasit;
      writeln(g,sum);
    End;
  close(g);
end.