Cod sursa(job #25060)

Utilizator andrei_blanaruAndrei Blanaru andrei_blanaru Data 4 martie 2007 10:20:37
Problema Kperm Scor 30
Compilator fpc Status done
Runda preONI 2007, Runda 3, Clasele 11-12 Marime 1.42 kb
const magic=666013;
var n,k,s,count:longword;
    v,x:array [1..100] of longword;

procedure back(p:integer);
var i:integer;
begin
  if p=n+1
    then  inc(count)
    else
  if p<=k
    then  for i:=1 to n do
            if (v[i]=0)and((k<>p)or((s+i)mod k=0))
              then  begin
                      v[i]:=1;
                      x[p]:=i;
                      inc(s,i);
                      back(p+1);
                      v[i]:=0;
                      dec(s,i);
                    end
              else
    else  begin
            i:=(x[p-k]-1) mod k+1;
            while i<=n do
              begin
                if v[i]=0
                  then  begin
                          v[i]:=1;
                          x[p]:=i;
                          back(p+1);
                          v[i]:=0;
                        end;
                inc(i,k);
              end;
          end;
end;

function fact(p:longword):longword;
var r,i:longword;
begin
  r:=1;
  for i:=2 to p do
    r:=(r*i)mod magic;
  fact:=r;
end;


begin
  assign(output,'kperm.out');
  rewrite(output);
  assign(input,'kperm.in');
  reset(input);
  readln(n,k);
  close(input);
  if k mod 2=0
    then  writeln(0)
    else  if k=n
            then  writeln(fact(n))
            else  begin
                    back(1);
                    writeln(count);
                  end;
  close(output);
end.