Cod sursa(job #9464)

Utilizator cimiCristina Stancu-Mara cimi Data 27 ianuarie 2007 15:38:56
Problema Secventa 5 Scor 80
Compilator fpc Status done
Runda Unirea 2007, clasele 11-12 Marime 1.89 kb
const
  lim=1050000;
var
  a,poz,catemax,catemin:array[1..lim] of longword;
  magicmax,magicmin,dif,u,v,k,i,j,n,lo,hi,x:longword;
  sol:int64;

procedure Sort(l, r: longword);
var
  i, j, x, y: longword;
begin
  i := l; j := r; x := a[(l+r) DIV 2];
  repeat
    while a[i] < x do i := i + 1;
    while x < a[j] do j := j - 1;
    if i <= j then
    begin
      y := a[i]; a[i] := a[j]; a[j] := y;
      y := poz[i]; poz[i] := poz[j]; poz[j] := y;
      i := i + 1; j := j - 1;
    end;
  until i > j;
  if l < j then Sort(l, j);
  if i < r then Sort(i, r);
end;

procedure Sortinvers(l, r: longword);
var
  i, j, x, y: longword;
begin
  i := l; j := r; x := poz[(l+r) DIV 2];
  repeat
    while poz[i] < x do i := i + 1;
    while x < poz[j] do j := j - 1;
    if i <= j then
    begin
      y := a[i]; a[i] := a[j]; a[j] := y;
      y := poz[i]; poz[i] := poz[j]; poz[j] := y;
      i := i + 1; j := j - 1;
    end;
  until i > j;
  if l < j then Sortinvers(l, j);
  if i < r then Sortinvers(i, r);
end;

begin
  assign(input,'secv5.in');
  reset(input);
  readln(n,lo,hi);
  for i:=1 to n do
  begin
    readln(a[i]);
    poz[i]:=i;
  end;
  sort(1,n);
  i:=1; k:=a[i]; j:=1;
  while i<=n do
  begin
    while (i<=n)and(a[i]=k) do
    begin
      a[i]:=j;
      inc(i);
    end;
    k:=a[i];
    inc(j);
  end;
  dif:=j-1;
  sortinvers(1,n);
  close(input);

  magicmax:=0; magicmin:=0; u:=1; v:=1;
  for i:=1 to n do
  begin
    x:=a[i];
    inc(catemax[x]);
    inc(catemin[x]);
    if catemax[x]=1 then inc(magicmax);
    if catemin[x]=1 then inc(magicmin);
    while magicmax>hi do
    begin
      dec(catemax[a[u]]);
      if catemax[a[u]]=0 then dec(magicmax);
      inc(u);
    end;
    while magicmin>lo-1 do
    begin
      dec(catemin[a[v]]);
      if catemin[a[v]]=0 then dec(magicmin);
      inc(v);
    end;
    sol:=sol+v-u;
  end;
  assign(output,'secv5.out');
  rewrite(output);
  writeln(sol);
  close(output);
end.