標籤:poj 3221 diamond puzzle. a diamond puzzle is
~~~~
題目連結:http://poj.org/problem?id=3221
顯然是BFS找最優解,可是終止條件不好寫,看到有一隻隊交上去一直TLE。
比賽完了看題解原來是以目標狀態為起點,BFS給每個狀態打表,用一個map映射存起來。
~~~~
#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>#include<string>#include<queue>#include<map>using namespace std;char str[10];char s[10]="0123456";map<string,int> v; //狀態映射map<string,int>ans; //答案映射struct node{ int t; char s[10];};//分別在0~6位置可以到達的目標位置,以-1結束。int dir[7][4]={ {2,4,6,-1},{2,6,-1},{1,0,3,-1},{2,4,-1}, {3,0,5,-1},{4,6,-1},{1,0,5,-1} };int Find(char* s){ for(int i=0;i<7;i++) if(s[i]=='0') return i;}int bfs(){ queue<node> q; node cur,next; strcpy(cur.s,s);cur.t=0; q.push(cur); v[cur.s]=1; ans[cur.s]=0; while(!q.empty()) { cur=q.front(); q.pop(); int pos=Find(cur.s); //'0'的位置。 for(int i=0;dir[pos][i]!=-1;i++) { char temp[10]; strcpy(temp,cur.s); //交換‘0’和和相應能去的位置 swap(temp[pos],temp[dir[pos][i]]); if(!v[temp]) { v[temp]=1; strcpy(next.s,temp); next.t=cur.t+1; ans[next.s]=next.t; q.push(next); } } }}int main(){ v.clear(); ans.clear(); bfs(); int T; scanf("%d",&T); while(T--) { scanf("%s",str); if(strcmp(str,s)==0) puts("0"); else printf("%d\n",ans[str]==0?-1:ans[str]); } return 0;}