MRECAMAN - Recaman’s Sequence

Tác giả: RR

Ngôn ngữ: Pascal

type
  list=^node;
  node=record
        u:longint;
        next:list;
  end;

procedure add(u:longint; var a:list);
    var
      p:list;
    begin
      new(p); p^.u:=u;
      p^.next:=a; a:=p;
    end;

const
  hashkey=1000003;

var
  h:array[0..hashkey] of list;
  a:array[0..500111] of longint;
  tmp,i:longint;

function find(u:longint):boolean;
    var
      p:list;
    begin
      p:=h[u mod hashkey];
      while p<>nil do
        begin
          if p^.u=u then exit(true);
          p:=p^.next;
        end;
      exit(false);
    end;

procedure insert(u:longint);
    var
      p:list;
    begin
      p:=h[u mod hashkey];
      while p<>nil do
        begin
          if p^.u=u then exit;
          p:=p^.next;
        end;
      add(u,h[u mod hashkey]);
    end;

begin
  a[0]:=0;
  for i:=1 to 500000 do
    begin
      tmp:=a[i-1]-i;
      if (tmp>0) and (not find(tmp)) then a[i]:=tmp
      else a[i]:=a[i-1]+i;
      insert(a[i]);
    end;

  read(i);
  while (i>=0) do
    begin
      writeln(a[i]);
      read(i);
    end;
end.

Download