acwing 1107 魔板

1107. 魔板 - AcWing题库

注意初始状态的初始化,以及每一个操作的转移

#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
#include<map>

using namespace std ;
map<string,pair<char,string> > pre ;
map<string,int> dist ;

int x[10] ; 
string get1(string a){
	//cout << s << endl ; 
	string res = "" ;
	for(int i = 0 ; i < 4 ; i ++) res += a[i+4] ;
	for(int i = 4 ; i < 8 ; i ++) res += a[i-4] ;
	return res ;
}
string get2(string a){
	string res = "" ;
	res += a[3] ; res += a[0] ; res += a[1]; res += a[2] ; 
	res += a[7] ; res += a[4] ; res+= a[5] ; res += a[6] ;
	return res ;
}
string get3(string a){
	string res = "" ;
	res+=a;
	res[1] = a[5];
	res[2] = a[1] ;
	res[5] = a[6] ;
	res[6] = a[2] ;
	return res ;
}
int bfs(string start,string e){
	if(start == e ) return 0 ;
	queue<string> q ;
	q.push(start) ;
	dist[start] = 0 ;
	
	while(!q.empty()){
		string now = q.front() ;
		q.pop() ;
		string s[3] ;
		s[0] = get1(now) ;
		s[1] = get2(now) ;
		s[2] = get3(now) ;
		
		for(int i = 0 ; i < 3 ; i ++){
			if(!dist.count(s[i])){
				dist[s[i]] = dist[now] + 1 ;
				pre[s[i]] = {'A'+i,now} ;
				q.push(s[i]) ;
				if(s[i] == e){
					return dist[e] ;
				}
			}
		}
	}
	
	return -1 ;
}
int main(){
	string start ;
	string e ;
	for(int i = 1 ; i <= 8 ; i ++){
		cin >> x[i] ;
	}
	for(int i = 1 ; i <= 4 ; i ++){
		e += (x[i]+'0') ;
	}
	for(int i = 8 ; i >= 5 ; i --){
		e += (x[i]+'0') ;
	}
	start = "12348765";
	//cout << e << endl << start << endl ;
	int step = bfs(start,e);
	cout << step  << endl;  
	string res ;
	while(start!=e){
		//cout << e << endl ;
		res += pre[e].first ;
		e = pre[e].second ;
	}
	reverse(res.begin(),res.end()) ;
	if(step>0)cout << res << endl ;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值