重写POJ1166

这次与上次不同,上次的初衷是想写BFS,然而却失败了,所以换用别的方便的但不普遍的方法。

这次决定就用BFS,整体框架还是比较简单的,问题还是要注意一下数据结构,其实最后写就可以了。

此外,还有BFS的回溯问题,也是比较简单的,如果担心边界问题,可以单独处理。

这次首先maxn小了,于是RTE

后来maxn大了,于是MLE

最后终于1万K过了。

其实只需要4^9次状态,maxn要20万+

 1 /**************************
 2     POJ 1166
 3     13956K
 4     469MS
 5     2015-06-26
 6     By JimmyLin
 7 **************************/
 8 #include<iostream>
 9 #include<cstdio>
10 #include<string>
11 #include<cstring>
12 
13 using namespace std;
14 const int maxn=300000;
15 struct node{
16     int a[9];
17     int choice,pnt;
18 };
19 node q[maxn];
20 string s[9]={
21     "ABDE",
22     "ABC",
23     "BCEF",
24     "ADG",
25     "BDEFH",
26     "CFI",
27     "DEGH",
28     "GHI",
29     "EFHI"
30 };
31 bool check(node p)
32 {
33     for(int i=0;i<9;i++)if(p.a[i])return false;
34     return true;
35 }
36 bool h[maxn];
37 bool hash(node p)
38 {
39     int base=1,tot=0;
40     for(int i=0;i<9;i++){
41         tot+=p.a[i]*base;
42         base*=4;
43     }
44     if(h[tot])return true;
45     else h[tot]=true;
46     return false;
47 }
48 int ans[maxn];
49 int tot=0;
50 int main()
51 {
52     memset(q,0,sizeof(q));
53     memset(h,0,sizeof(h));
54     int front=1,back=1;
55     for(int i=0;i<9;i++)cin>>q[1].a[i];
56     while(front<=back){
57         node p=q[front];
58         front++;
59         if(check(p)){
60             while(p.pnt){
61                 ans[tot++]=p.choice;
62                 p=q[p.pnt];
63             }
64             for(int i=tot-1;i>=1;i--)cout<<ans[i]<<' ';
65             cout<<ans[0]<<endl;
66             break;
67         }
68         for(int i=0;i<9;i++){
69             node p1=p;
70             for(int j=0;j<s[i].length();j++)p1.a[s[i][j]-'A']=(p1.a[s[i][j]-'A']+1)%4;
71             if(hash(p1))continue;
72             back++;
73             for(int j=0;j<9;j++)q[back].a[j]=p1.a[j];
74             q[back].pnt=front-1;
75             q[back].choice=i+1;
76         }
77     }
78     return 0;
79 }

 

posted @ 2015-06-26 21:45  JimmyLin^_^  阅读(193)  评论(0编辑  收藏  举报