为什么我的代码用 c++20 提交超时,c++14 AC
代码:
#include<bits/stdc++.h>
using namespace std;
int a[3][3];
string End;
string to_str(int tmp[3][3]) {
string str;
for (int i=0;i<3;i++)
for (int j=0;j<3;j++) str += tmp[i][j]+'0';
return str;
}
void output(unordered_map<string,string> ans) {
string begin=to_str(a);
stack<string> out;
for (string str=End;;str=ans[str]) {
out.push(str);
if (str == begin) break;
}
while (!out.empty()) {
string tmp=out.top(); out.pop();
cout << tmp[0] << " " << tmp[1] << " " << tmp[2] << '\n';
cout << tmp[3] << " " << tmp[4] << " " << tmp[5] << '\n';
cout << tmp[6] << " " << tmp[7] << " " << tmp[8] << "\n\n";
}
}
string opt1(string str) {
char tmp=str[0];
str[0]=str[3]; str[3]=str[6]; str[6]=str[7];
str[7]=str[8]; str[8]=str[5]; str[5]=str[2];
str[2]=str[1]; str[1]=tmp;
return str;
}
string opt2(string str) {
swap(str[3],str[5]);
swap(str[4],str[5]);
return str;
}
void bfs() {
queue<pair<string,int> > q;
unordered_map<string,string> ans;
unordered_map<string,bool> maps;
q.push({to_str(a),0}); maps[to_str(a)]=1;
while (!q.empty()) {
pair<string,int> tmp=q.front(); q.pop();
if (tmp.first == End) {
cout << tmp.second << '\n';
output(ans);
exit(0);
}
string t1=opt1(tmp.first);
string t2=opt2(tmp.first);
if (!maps[t1]) {
maps[t1]=1; ans[t1]=tmp.first;
q.push({t1,tmp.second+1});
}
if (!maps[t2]) {
maps[t2]=1; ans[t2]=tmp.first;
q.push({t2,tmp.second+1});
}
}
}
int main()
{
for (int i=0;i<=8;i++) End += i+'0';
for (int i=0;i<3;i++)
for (int j=0;j<3;j++) cin >> a[i][j];
bfs();
cout << "UNSOLVABLE";
return 0;
}