Cod sursa(job #56823)

Utilizator ProtomanAndrei Purice Protoman Data 30 aprilie 2007 16:11:02
Problema Castel Scor 0
Compilator fpc Status done
Runda Arhiva de probleme Marime 2.73 kb
var l:array[0..2251,0..2251] of longint;
    u,a:array[1..2251] of longint;
    v:array[0..151,0..151] of longint;
    q:array[0..500000] of longint;
    x,y,i,j,ic,ind,m,n,k,h,nr:longint;
    f1,f2:text;

procedure vecini(y:longint);
begin
if u[y]=0 then
begin
        if u[a[y]]=1 then
        begin
                h:=1;
                u[y]:=1;
                for j:=ic to ind do
                if y=q[j] then h:=0;
                        if h=1 then
                        begin
                                inc(ind);
                                q[ind]:=y;
                        end;
         end
         else
         begin
                h:=1;
                for j:=1 to l[a[y],0] do
                if y=l[a[y],j] then h:=0;
                        if h=1 then
                        begin
                                inc(l[a[y],0]);
                                l[a[y],l[a[y],0]]:=y;
                        end;
         end;
end;
end;

begin
        assign(f1,'castel.in');
        reset(f1);
        assign(f2,'castel.out');
        rewrite(f2);
        read(f1,n,m,k);
        for i:=1 to n do
                for j:=1 to m do
                begin
                        read(f1,v[i,j]);
                        a[(i-1)*m+j]:=v[i,j];
                end;
        u[k]:=1;
        q[1]:=k;
        ind:=1;
        ic:=1;
        while ind>=ic do
        begin
                inc(ic);
                x:=q[ic-1];
                for i:=1 to l[x,0] do
                begin
                        h:=1;
                        u[i]:=1;
                        for j:=ic to ind do
                        if i=q[j] then h:=0;
                        if h=1 then
                        begin
                                inc(ind);
                                q[ind]:=i;
                        end;
                end;
                vecini(x-m);
                vecini(x+m);
                vecini(x-1);
                vecini(x+1);
                if u[y]=0 then
                begin
                        if u[a[y]]=1 then
                        begin
                                 h:=1;
                                 u[y]:=1;
                                 for j:=ic to ind do
                                 if i=q[j] then h:=0;
                                 if h=1 then
                                 begin
                                        inc(ind);
                                        q[ind]:=i;
                                 end;
                        end;
                end;
        end;
        for i:=1 to 2250 do if u[i]=1 then inc(nr);
        writeln(f2,nr);
        close(f1);
        close(f2);
end.