USACO1.4.2(The clocks)BFS

Descriptionhtml

考虑将如此安排在一个 3 x3 行列中的九个时钟:ios

目标要找一个最小的移动顺序次将全部的指针指向12点。 下面原表格列出了9种不一样的旋转指针的方法,每一种方法都叫一次移动。 选择1到9号移动方法,将会使在表格中对应的时钟的指针顺时针旋转90度。 移动方法 受影响的时钟 1 ABDE 2 ABC 3 BCEF 4 ADG 5 BDEFH 6 CFI 7 DEGH 8 GHI 9 EFHI Example数组

[但这可能不是正确的方法,请看下面]函数

Inputpost

第1-3行: 三个空格分开的数字,每一个数字表示一个时钟的初始时间,3,6,9,12。 数字的含意和上面第一个例子同样。spa

Output指针

单独的一行包括一个用空格分开的将全部指针指向12:00的最短移动顺序的列表。 若是有多种方案,输出那种使的链接起来数字最小的方案。(举例来讲5 2 4 6 < 9 3 1 1)。code

Single Inputhtm

9 9 12 blog

6 6 6

6 3 6

Single Output

4 5 8 9

自定义  状态  类型,并定义状态数组,而查找时使用哈希查找表。具体代码以下:

 1 #include<iostream>
 2 #include<cstring>
 3 #define mem(a) memset(a,0,sizeof(a));
 4 using namespace std;
 5 typedef int State[9];//定义“状态”类型
 6 const int MAXN=320000;//定义最大状态
 7 const int MAXSIZE=100003;//哈希表的最大范围
 8 int head[MAXSIZE],fa[MAXN],next[MAXN],move[MAXN];//head为哈希表中的头结点,next为哈希值相同时组成的链表,fa时父节点,move记录变化时所取的值
 9 State st[MAXN];//状态数组,全部状态都保存在这里
10 const State goal={3,3,3,3,3,3,3,3,3};//目标状态,4个时间3,6,9,12依次转化为0,1,2,3;因此目标状态是9个3
11 const char mo[9][6]={"abde","abc","bcef","adg","bdefh","cfi","degh","ghi","efhi"};//移动的钟
12 
13 void shuru()//输入并转化为0,1,2,3
14 {
15     mem(head);mem(next);//置0
16     int i;
17     for(i=0;i<9;i++){cin>>st[0][i];st[0][i]=st[0][i]/3-1;}
18 }
19 int hash(State& s)//定义哈希函数
20 {
21     int i,a=0;
22     for(i=0;i<9;i++)a=a*10+s[i];//随便算,好比把几个数字转化成9位数
23     return a%MAXSIZE;//确保哈希函数值是不超过表大小的非负正整数
24 }
25 bool insert(int a)//尝试插入
26 {
27     int h=hash(st[a]);
28     int u=head[h];
29     while(u)//从表头开始查找链表
30     {
31         if(memcmp(st[u],st[a],sizeof(st[a]))==0)return false;//找到了,插入失败
32         u=next[u];//顺着链表继续查找
33     }
34     next[a]=head[h];//插入到链表中
35     head[h]=a;
36     return true;
37 }
38 void print(int p)//打印
39 {
40     if(!fa[p]){cout<<move[p];return ;}
41     print(fa[p]);
42     cout<<" "<<move[p];
43 }
44 void bfs()//BFS宽搜
45 {
46     int rear=1,front=0;
47     for(;;)
48     {
49         State& s=st[front];
50         if(memcmp(s,goal,sizeof(goal))==0){print(front);cout<<endl;return ;}//一旦找到就打印并结束搜索
51         int i;
52         for(i=0;i<9;i++)//从1到9依次变化
53         {
54             State& t=st[rear];
55             memcpy(&t,&s,sizeof(s));
56             int len=strlen(mo[i]),j;
57             for(j=0;j<len;j++)
58                 t[mo[i][j]-'a']=(t[mo[i][j]-'a']+1)%4;
59             if(insert(rear)){move[rear]=i+1;fa[rear++]=front;}//能够插入,记录并队列尾加1
60         }
61         front++;
62     }
63 }
64 int main()
65 {
66     shuru();
67     bfs();
68     return 0;
69 }

 

转载于:https://www.cnblogs.com/gj-Acit/archive/2013/02/12/2910277.html