Cod sursa(job #197662)

Utilizator ProtomanAndrei Purice Protoman Data 5 iulie 2008 13:37:40
Problema Gropi Scor 50
Compilator fpc Status done
Runda Junior Challenge 2008 Marime 2.57 kb
var f1,f2:text;
    ok:boolean;
    i,j,n,m,c,stx,sty,fnx,fny,af,sol:longint;
    gx,gy:array[0..100010] of longint;
    g:array[0..2,0..100010] of longint;

procedure swap(var x,y:longint);
var aux:longint;
begin
        aux:=x;
        x:=y;
        y:=aux;
end;

procedure pozitie(var m:longint; p,u:longint);
var i,j,di,dj,aux:longint;
begin
        i:=p;
        j:=u;
        di:=0;
        dj:=-1;
        while i<>j do
        begin
                if (gx[i]>gx[j])or((gx[i]=gx[j])and(gy[i]>gy[j])) then
                begin
                        swap(gx[i],gx[j]);
                        swap(gy[i],gy[j]);
                        aux:=di;
                        di:=-dj;
                        dj:=-aux;
                end;
                i:=i+di;
                j:=j+dj;
        end;
        m:=i;
end;

procedure quick(p,u:longint);
var m:longint;
begin
        if p<u then
        begin
                pozitie(m,p,u);
                quick(p,m-1);
                quick(m+1,u);
        end;
end;

procedure cauta(loc,p,u:longint);
var m:longint;
begin
        if p>u then
                exit;
        m:=(p+u) div 2;
        if g[loc,m]>sty then
        begin
                af:=g[loc,m];
                cauta(loc,p,m-1);
        end
        else cauta(loc,m+1,u);
end;

begin
        assign(f1,'gropi.in');
        reset(f1);
        assign(f2,'gropi.out');
        rewrite(f2);
        read(f1,c,n);
        for i:=1 to n do
                read(f1,gx[i],gy[i]);
        quick(1,n);
        for i:=1 to n do
        begin
                inc(g[gx[i],0]);
                g[gx[i],g[gx[i],0]]:=gy[i];
        end;
        inc(g[1,0]);
        inc(g[2,0]);
        g[1,g[1,0]]:=maxlongint;
        g[2,g[2,0]]:=maxlongint;
        read(f1,m);
        for i:=1 to m do
        begin
                read(f1,stx,sty,fnx,fny);
                if sty>fny then
                begin
                        swap(stx,fnx);
                        swap(sty,fny);
                end;
                sol:=fny-sty+1;
                ok:=true;
                while ok do
                begin
                        cauta(stx,1,g[stx,0]);
                        if fny<af then
                                break;
                        inc(sol);
                        stx:=stx and 1+1;
                        sty:=af-1;
                end;
                if stx<>fnx then
                        inc(sol);
                writeln(f2,sol);
        end;
        close(f1);
        close(f2);
end.