Acwing-魔板

100 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第14天,点击查看活动详情

Rubik 先生在发明了风靡全球的魔方之后,又发明了它的二维版本——魔板。

这是一张有 8 个大小相同的格子的魔板:

1 2 3 4
8 7 6 5

我们知道魔板的每一个方格都有一种颜色。

这 8种颜色用前 8 个正整数来表示。

可以用颜色的序列来表示一种魔板状态,规定从魔板的左上角开始,沿顺时针方向依次取出整数,构成一个颜色序列。

对于上图的魔板状态,我们用序列 (1,2,3,4,5,6,7,8)来表示,这是基本状态。

这里提供三种基本操作,分别用大写字母 A,B,C 来表示(可以通过这些操作改变魔板的状态):

A:交换上下两行;
B:将最右边的一列插入到最左边;
C:魔板中央对的4个数作顺时针旋转。

下面是对基本状态进行操作的示范:

A:

8 7 6 5
1 2 3 4

B:

4 1 2 3
5 8 7 6

C:

1 7 2 4
8 6 3 5

对于每种可能的状态,这三种基本操作都可以使用。

你要编程计算用最少的基本操作完成基本状态到特殊状态的转换,输出基本操作序列。

注意:数据保证一定有解。

输入格式

输入仅一行,包括 8 个整数,用空格分开,表示目标状态。

输出格式

输出文件的第一行包括一个整数,表示最短操作序列的长度。

如果操作序列的长度大于0,则在第二行输出字典序最小的操作序列。

数据范围

输入数据中的所有数字均为 1 到 8 之间的整数。

输入样例:

2 6 8 4 5 7 3 1

输出样例:

7
BCABCCB

分析

这是一道比较隐晦的BFSBFS,跟八数码那题有一点点像,就是关于一个状态变换,关于状态变换,因为只有把8个数,我们可以把位置标出来,然后直接模拟,关于这题,还要感谢并查集姐姐,告诉我这个C++语法fw取地址符的相关知识,所以三个操作就直接用手动模拟,起始状态是12345678,终了状态输入,每次都将三个操作之后没有出现过的状态入队,记录路径可以用unorderedmapunordered-map,最后记住要反向输出因为whilewhile循环。

代码

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string> 
#include <queue>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <stack> 
#include <cmath>
#include <iomanip>
#define ll long long
#define AC return
#define Please 0
using namespace std;
const int N=1010;
const double esp=1e-8;
typedef pair<int,int>PII;
typedef unsigned long long ull; 
int n,m,t;
unordered_map<string, pair<char, string>> pre;
inline int read(){//快读 
    int x=0,f=1;char ch=getchar();
    while(ch<'0' || ch>'9'){
        if(ch=='-') f=-1;
        ch=getchar();
    }
    while(ch>='0' && ch<='9'){
        x=x*10+ch-'0'; 
        ch=getchar();
    }
    AC x*f;
}
string opa(string s){
	for(int i=0;i<=3;i++){
		swap(s[i],s[7-i]);
	}
	return s;
} 
string opb(string s){
	swap(s[3],s[2]);
	swap(s[2],s[1]);
	swap(s[1],s[0]);
	swap(s[4],s[5]);
	swap(s[5],s[6]);
	swap(s[6],s[7]);
	return s;
}
string opc(string s){
	swap(s[1],s[2]);
	swap(s[5],s[6]);
	swap(s[1],s[5]);
	return s;
}
map<string,int>mp;
inline void bfs(string s){
	queue<string> q;
	mp.clear();
	mp[s]=0;
	q.push(s);
	while(q.size()){
		string t=q.front();
		q.pop();
		if(!mp.count(opa(t))){
			mp[opa(t)]=mp[t]+1;
			q.push(opa(t));
			pre[opa(t)]={'A',t};
		}
		if(!mp.count(opb(t))){
			mp[opb(t)]=mp[t]+1;
			q.push(opb(t));
			pre[opb(t)]={'B',t}; 
		}
		if(!mp.count(opc(t))){
			mp[opc(t)]=mp[t]+1;
			q.push(opc(t));
			pre[opc(t)]={'C',t};
		}
	}
}
int main(){
    string ss="12345678"; 
	string se="";
	for(int i=0;i<8;i++){
		int x;
		x=read();
		se+=x+'0';
	}
	bfs(ss);
	int ans=mp[se];
	cout<<ans<<endl;
	string res="";
	while(se!=ss){
		res+=pre[se].first;
		se=pre[se].second;
	}
	if(ans>0){
		//cout<<res<<endl;
		for(int i=0;i<res.size();i++){
			cout<<res[res.size()-i-1];
		}
	}
	return 0;
}

希望能帮助到大家(QAQQAQ)!