求助,BFS每次只能拓展4步
查看原帖
求助,BFS每次只能拓展4步
1183074
xzy_AK_IOI楼主2024/8/25 12:17
#include<bits/stdc++.h>
using namespace std;
const string from="12345678";
map <string,string> last;
map <string,char> last_bu;
bool mp[1000000];
int Pow[30]={1};
int contor(string b){
	int sum=1;
	int ans;
	for (int i=0;i<=7;i++){
		ans=0;
		for (int j=i+1;j<=7;j++){
			if (b[j]<b[i]) ans++;
		}
		sum+=ans*Pow[7-i];
	}
	return sum;
}
struct node{
	string ban;
	int step;
};
string to,j;
char a;
string A(string f){
	string s=f;
	swap(s[3],s[4]);
	swap(s[2],s[5]);
	swap(s[1],s[6]);
	swap(s[0],s[7]);
	return s;
}
string B(string f){
	string s=f;
	swap(s[0],s[3]);
	swap(s[4],s[7]);
	return s;
}
string C(string f){
	string s=f;
	char b=s[1];
	s[1]=s[6];
	s[6]=s[5];
	s[5]=s[2];
	s[2]=b;
	return s;
}
void print_path(int Step){
	cout<<Step<<'\n';
	stack <char> s;
	string now=to;
	while (now!=from){
		s.push(last_bu[now]);
		now=last[now];
	}
	while (!s.empty()){
		cout<<s.top();
		s.pop();
	}
	exit(0);
}
void bfs(){
	queue <node> q;
	q.push((node){from,0});
	mp[contor(from)]=1;
	while (!q.empty()){
		//cout<<q.size()<<'\n';
		node v=q.front();q.pop();
		string l;
		//cout<<v.ban<<" "<<v.step<<" "<<last_bu[v.ban]<<" "<<last[v.ban]<<'\n';
		l=A(v.ban);
		if (!mp[contor(l)]){
			mp[contor(l)]=1;
			last[l]=v.ban;
			last_bu[l]='A';
			q.push((node){l,v.step+1});
			if (l==to) print_path(v.step+1);
		}
		l=B(v.ban);
		if (!mp[contor(l)]){
			mp[contor(l)]=1;
			last[l]=v.ban;
			last_bu[l]='B';
			q.push((node){l,v.step+1});
			if (l==to) print_path(v.step+1);
		}
		l=C(v.ban);
		if (!mp[contor(l)]){
			mp[contor(l)]=1;
			last[l]=v.ban;
			last_bu[l]='C';
			q.push((node){l,v.step+1});
			if (l==to) print_path(v.step+1);
		}
	}
}
signed main()
{
	for (int i=1;i<=25;i++) Pow[i]=Pow[i-1]*i;
	for (int i=1;i<=8;i++) {cin>>a;to+=a;}
	bfs();
	return 0;
}
2024/8/25 12:17
加载中...