吃完晚饭,啃着tomato来poj上提交,结果不支持unordered_map,吐血啦,看来还是要用BFS+康托展开,还想再写一篇双向BFS的,对这道题算是圆满了*_*,但是要用G++提交,C++会报错我也不知道为嘛
#include<iostream> #include<cstring> #include<queue> #include<unordered_map> using namespace std; typedef pair<int,string> pii; int dir[4][2]={{-1,0},{1,0},{0,1},{0,-1}}; char op[]="lrdu"; char ch; string start,s; int f(string state){ int ans=0; for(int i=0;i<9;i++){ if(state[i]=='x') continue; int t=state[i]-'1'; ans+=abs(i%3-t%3)+abs(i/3-t/3); } return ans; } string Astar(){ string end="12345678x"; unordered_map<string,int> dist; unordered_map<string,pair<char,string> > prev; priority_queue<pii,vector<pii>,greater<pii> > heap; dist[start]=0; heap.push({f(start),start}); while(!heap.empty()){ auto t=heap.top(); heap.pop(); string state=t.second; if(state==end) break; int x,y; for(int i=0;i<9;i++){ if(state[i]=='x'){ x=i%3; y=i/3; break; } } string source=state; for(int i=0;i<4;i++){ int dx=x+dir[i][0]; int dy=y+dir[i][1]; if(dx<0 || dx>2 || dy<0 || dy>2) continue; swap(state[x+y*3],state[dx+dy*3]); if(!dist.count(state) || dist[state]>dist[source]+1){ dist[state]=dist[source]+1; prev[state]={op[i],source}; heap.push({dist[state]+f(state),state}); } state=source; } } string ans; while(end!=start){ ans=prev[end].first+ans; end=prev[end].second; } return ans; } signed main(){ ios::sync_with_stdio(false); cin.tie(0);cout.tie(0); for(int i=0;i<9;i++){ cin>>ch; start+=ch; if(ch!='x') s+=ch; } int cnt=0; for(int i=0;i<8;i++){ for(int j=i+1;j<8;j++){ if(s[i]>s[j]) cnt++; } } if(cnt&1) puts("unsolvable"); else cout<<Astar()<<endl; return 0; }
标签:ch,dist,int,1077,BFS,start,state,Eight,heap From: https://www.cnblogs.com/accbulb/p/18007039