搜索/sgu 125 Shtirlits

题意

  给出一个n*n的数组b,b[i,j]表示在数组a中,比a[i,j]大的上下左右一共有多少个

  求一个满足b的a

分析

  数据范围n<=4,很明显,深搜

  对于每一个格子,从1~n*n枚举,在检查上一个合法之后,进行下一步的搜索

Accepted Code

 1 {
 2         PROBLEM:sgu125
 3         AUTHER:Rinyo
 4         MEMO:深搜 
 5 }
 6 Program sgu125;
 7 Const
 8   Infile = 'sgu125.in';
 9   Outfile = 'sgu125.out';
10   dx:Array[1..4]Of Longint=(-1,1,0,0);
11   dy:Array[1..4]Of Longint=(0,0,-1,1);
12 Var
13   a,b:Array[0..4,0..4]Of Longint;
14   n,i,j:Longint;
15   flag:Boolean;
16 Function check(x,y:Longint):Boolean;
17 Var
18   ans,i,xx,yy:Longint;
19 Begin
20   ans:=0;
21   For i:=1 To 4 Do Begin
22     xx:=x+dx[i];yy:=y+dy[i];
23     If a[xx,yy]>a[x,y] Then Inc(ans);
24   End;
25   If ans=b[x,y] Then check:=true Else check:=false;
26 End;
27 Procedure dfs(x,y:Longint);
28 Var
29   i,j:Longint;
30 Begin
31   If x=n+1 Then BEgin
32     For i:=1 To n Do
33       If not check(n,i) Then Exit;
34     flag:=true;
35     Exit;
36   End;
37   For i:=1 To n*n Do Begin
38     a[x,y]:=i;
39     If (x=1) Or check(x-1,y) Then Begin
40       If (y=n) Then dfs(x+1,1) Else dfs(x,y+1);
41       If flag Then Exit;
42     End;
43   End;
44 End;
45 Begin
46   Assign(input,infile);Reset(input);
47   Assign(output,outfile);Rewrite(output);
48   ReadLn(n);
49   For i:=1 To n Do Begin
50     For j:=1 To n Do Read(b[i,j]);
51     ReadLn;
52   End;
53   flag:=false;
54   dfs(1,1);
55   If not flag Then WriteLn('NO SOLUTION')
56               Else Begin
57                 For i:=1 To n Do Begin
58                   For j:=1 To n-1 Do Write(a[i,j],' ');
59                   WriteLn(a[i,n]);
60                 End;
61               ENd;
62   Close(input);Close(output);
63 End.

 

posted @ 2013-03-20 20:59  Rinyo  阅读(378)  评论(0编辑  收藏  举报