终于到第一张最后一题了!不过最后一题果然有些难度,虽然是老问题“八皇后”,但是对于从没写过深搜的我来说还是一个挑战。好不容易花了很长时间写正确了深搜,结果也很在意料之中的超时,剪枝的话嫌太麻烦,于是去网上找优化方法,原来有一种叫做位操作的方法可以大大缩短时间,研究了一阵子才搞懂。这里感谢freddy's Blog,在那里借鉴了很多。我还会再改一改代码以更符合我的风格。下面贴出代码,以作纪念。

View Code
 1 /*{
 2 ID:jzy3209981
 3 PROG:checker
 4 LANG:C++
 5 }*/
 6 #include<stdio.h>
 7 #include<iostream>
 8 #include<string.h>
 9 #include<stdlib.h>
10 #include<math.h>
11 using namespace std;
12 int result=0;
13 double deep[14];
14 void dfs(int a,int n,int rowc,int lc,int rc)
15 {
16     int i;
17 
18     int sign=((1<<n)-1);    
19     int row,l,r,p,po;
20     row=rowc;
21     l=lc;
22     r=rc;
23     if(row!=sign)
24     {
25         po=sign&~(row|lc|rc);
26         while(po!=0)
27         {
28             p=po&-po;
29             po-=p;        
30             deep[a]=p;        
31             dfs(a+1,n,row+p,(l+p)<<1,(r+p)>>1);        
32         }
33     }
34     else
35     {
36         if(result<3)                
37             for(i=0;i<n;i++)
38             {
39                 if(i!=n-1)
40                     printf("%.0f ",log(deep[i])/log(2)+1);
41                 else
42                     printf("%.0f\n",log(deep[i])/log(2)+1);
43             }
44         result++;
45     }
46 }
47 int main()
48 {
49         freopen ("checker.in","r",stdin);
50         freopen ("checker.out","w",stdout);
51     int n,a=0;
52     scanf("%d",&n);
53     dfs(a,n,0,0,0);
54     printf("%d\n",result);
55     return 0;
56 }

 

posted on 2012-07-18 10:47  醉春雨  阅读(157)  评论(0)    收藏  举报