Cod sursa(job #57048)
Utilizator | Data | 30 aprilie 2007 23:11:56 | |
---|---|---|---|
Problema | Castel | Scor | 30 |
Compilator | fpc | Status | done |
Runda | Arhiva de probleme | Marime | 2.63 kb |
var l:array[0..22510,0..22510] of word;
u,a:array[1..2251] of longint;
v:array[0..151,0..151] of longint;
q:array[1..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;
y:=0;
nr:=0;
u[k]:=1;
q[1]:=k;
ind:=1;
ic:=1;
while ind>=ic do
begin
inc(ic);
x:=q[ic-1];
u[x]:=1;
for i:=1 to l[x,0] do
begin
h:=1;
u[i]:=1;
inc(ind);
q[ind]:=l[x,i];
end;
vecini(x-m);
vecini(x+m);
if (x-1) mod m<>0 then vecini(x-1);
if x mod m<>0 then 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.