USACO 6.5.5 Checker Challenge 位运算+dfs

这题就是n皇后问题,用位运算的dfs秒掉就好了。

{
IDL: ymwbegi1
PROG: checker
LANG: PASCAL
} 

var
  n,ans,s:longint;
  f:array[1..13] of longint;

procedure print;
var
  i,s,x:longint;
begin
  for i:=1 to n do
  begin
    x:=f[i];
    s:=0;
    while x>0 do
    begin
      inc(s);
      x:=x div 2;
    end;
    if i<n
      then write(s,' ')
      else writeln(s);
  end;
end;

procedure dfs(row,dl,dr,x:longint);
var
  p,q:longint;
begin
  if row=1 shl n-1 then
  begin
    if s<3 then
    begin
      inc(s);
      print;
    end;
    inc(ans);
    exit;
  end;
  p:=((row or dl or dr) xor (1 shl n-1)) and (1 shl n-1);
  while p>0 do
  begin
    q:=p and (-p);
    f[x]:=q;
    dfs(row+q,(dl+q) shl 1,(dr+q) shr 1,x+1);
    p:=p-q;
  end;
end;

begin
  assign(input,'checker.in');
  assign(output,'checker.out');
  reset(input);
  rewrite(output);
  readln(n);
  dfs(0,0,0,1);
  writeln(ans);
  close(input);
  close(output);
end.


你可能感兴趣的:(USACO 6.5.5 Checker Challenge 位运算+dfs)