力帆总裁牟刚是哪里人:n皇后问题求助

来源:百度文库 编辑:查人人中国名人网 时间:2024/05/07 12:26:56
小弟在usaco上做到Checker Challenge 发现和n皇后问题相似
于是用回溯打上了n皇后 结果在12个皇后时超时了(限时1s 我用时2s)
请问有什么可以优化的地方吗?或者说除了回溯有更好的方法吗?
如果放上源码小弟就更加感激不尽了

是用回溯
需要优化
PASCAL代码:[剪枝部分较复杂]
program checker;
const
maxn=13;
var
fin,fout:text;
ans:array[1..3,1..maxn]of byte;
s:array[1..maxn]of byte;
pre,next:array[0..maxn+1]of byte;
pie:array[2..maxn*2]of boolean;
na:array[1-maxn..maxn-1]of boolean;
n,i,j,total:longint;
procedure search(x:byte);
var
y:byte;
begin
y:=0;
repeat
y:=next[y];
if y>n then exit;
if not pie[x+y] and not na[x-y] then begin
pie[x+y]:=true;na[x-y]:=true;
pre[next[y]]:=pre[y];next[pre[y]]:=next[y];
s[x]:=y;
if x=n then begin
inc(total);
if total<4 then ans[total]:=s;
end
else
search(x+1);
pie[x+y]:=false;na[x-y]:=false;
pre[next[y]]:=y;next[pre[y]]:=y;
end;
until false;
end;
procedure start(y:byte);
begin
if not pie[1+y] and not na[1-y] then begin //Here it's true of course
pie[1+y]:=true;na[1-y]:=true;
pre[next[y]]:=pre[y];next[pre[y]]:=next[y];
s[1]:=y;
search(2);
pie[1+y]:=false;na[1-y]:=false;
pre[next[y]]:=y;next[pre[y]]:=y;
end;
end;
begin
assign(fin,'checker.in');
reset(fin);
read(fin,n);
close(fin);

for i:=1 to n do begin
pre[i]:=i-1;next[i]:=i+1;
end;
pre[n+1]:=n;next[0]:=1;
if n=6 then
for i:=1 to 6 do
start(i)
else begin
for i:=1 to n shr 1 do
start(i);
total:=total*2;
if odd(n) then start(n shr 1+1);
end;

assign(fout,'checker.out');
rewrite(fout);
for i:=1 to 3 do begin
for j:=1 to n-1 do
write(fout,ans[i,j],' ');
writeln(fout,ans[i,n]);
end;
writeln(fout,total);
close(fout);
end.

meiyoubanfa