Cod sursa(job #778651)

Utilizator t.g.g.tt.g.g.t t.g.g.t Data 15 august 2012 12:41:19
Problema Secv Scor 70
Compilator fpc Status done
Runda Arhiva de probleme Marime 1.24 kb
var a,b:array[0..5000]of longint; i,j,n,k,k1,j2,s,k2:integer; t:boolean;
procedure quicksort (ins,sf:integer);
var i,s:integer; pivot,k:longint;
begin
  i:=ins; s:=sf; pivot:=a[(i+s) div 2];
  repeat
    while pivot>a[i] do inc(i);
    while pivot<a[s] do dec(s);
    if i<=s then begin k:=a[i]; a[i]:=a[s]; a[s]:=k; inc(i); dec(s) end;
  until i>s;
if (s>ins) then quicksort(ins,s);
if (i<sf)then quicksort(i,sf);
end;
begin
assign(input,'secv.in'); reset(input);
read(n);
for i:=1 to n do begin read(a[i]); b[i]:=a[i];end;
quicksort(1,n);j:=1;k:=0; for i:=1 to n do if b[i]=a[1] then if k=0 then k:=i; s:=5001;
assign(output,'secv.out'); rewrite(output); a[n+1]:=-1;
while a[j]=a[1] do
  begin
    k1:=k; k2:=k; k:=0;
    if k1<>0 then
    for i:=j+1 to n do
      if a[i]<>a[i-1] then
        begin
          j2:=k2;
          while (b[j2]<>a[i]) and (j2<n) do begin inc(j2); if b[j2]=a[1] then if k=0 then k:=j2 end;
          if b[j2]=a[i] then k2:=j2;
        end;
        if k=0 then begin k:=k2; while (k<n) and (b[k]<>a[1]) do inc(k); end;
    if b[k2]=a[n] then begin t:=true;
    if s>k2-k1 then s:=k2-k1; end;
    inc(j);
  end;
if t then if n=0 then writeln('0') else writeln(s+1) else writeln('-1');
close(output);
end.