直接dfs就好了,并不用什么优化,因为时限是5s……
代码:
{ ID: ymwbegi1 PROG: wissqu LANG: PASCAL } const dl:array[1..5] of longint=(3,3,3,4,3); ch:array[1..1] of longint=(4); var i,j,ans:longint; flag:boolean; f,ansf:array[1..16,1..3] of longint; s:array[1..5,1..4,1..4] of longint; v:array[1..4,1..4] of boolean; a:array[1..4,1..4] of longint; d:array[1..5] of longint; c:char; function min(x,y:longint):longint; begin if x<y then exit(x) else exit(y); end; function max(x,y:longint):longint; begin if x>y then exit(x) else exit(y); end; procedure work(z,x,y,w:longint); var i,j:longint; begin for i:=max(x-1,1) to min(x+1,4) do for j:=max(y-1,1) to min(y+1,4) do inc(s[z,i,j],w); end; procedure print; var i:longint; begin for i:=1 to 16 do writeln(chr(ansf[i,1]+ord('A')-1),' ',ansf[i,2],' ',ansf[i,3]); writeln(ans); end; procedure dfs(x:longint); var i,j,k:longint; begin if x=17 then begin inc(ans); if flag then begin ansf:=f; flag:=false; end; exit; end; if x<2 then begin for i:=1 to 4 do for j:=1 to 4 do if (s[ch[x],i,j]=0)and(v[i,j]) then begin f[x,1]:=ch[x]; f[x,2]:=i; f[x,3]:=j; v[i,j]:=false; work(a[i,j],i,j,-1); work(ch[x],i,j,1); inc(d[ch[x]]); dfs(x+1); v[i,j]:=true; work(ch[x],i,j,-1); work(a[i,j],i,j,1); dec(d[ch[x]]); end; end else for k:=1 to 5 do if d[k]<dl[k] then for i:=1 to 4 do for j:=1 to 4 do if (s[k,i,j]=0)and(v[i,j]) then begin f[x,1]:=k; f[x,2]:=i; f[x,3]:=j; work(k,i,j,1); work(a[i,j],i,j,-1); inc(d[k]); v[i,j]:=false; dfs(x+1); v[i,j]:=true; work(k,i,j,-1); work(a[i,j],i,j,1); dec(d[k]); end; end; begin assign(input,'wissqu.in'); assign(output,'wissqu.out'); reset(input); rewrite(output); for i:=1 to 4 do for j:=1 to 4 do begin if j<4 then read(c) else readln(c); a[i,j]:=ord(c)-ord('A')+1; work(a[i,j],i,j,1); end; flag:=true; fillchar(v,sizeof(v),true); dfs(1); print; close(input); close(output); end.