题目大意:给出两个色子,只能进行四种操作,左转,右转,上转,下转,问能否经过旋转使两个色子的各面都相同

解题思路:直接暴力,用vis数组表示是否搜索过,这种解法接近1S,有点悬

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#define maxn 700000
using namespace std;
const int Z[4][6] = {{2,3,1,0,4,5},{3,2,0,1,4,5},{5,4,2,3,0,1},{4,5,2,3,1,0}};
struct Dice{
	int statu[6], time;
}D;
int A[6], B[6], vis[maxn], End, ans;
bool solve() {
	queue<Dice> q;
	for(int i = 0; i < 6; i++)
		D.statu[i] = B[i];
	D.time = 0;
	q.push(D);
	while(!q.empty()) {
		Dice tmp = q.front();
		q.pop();
		int num = 0;
		for(int i = 0; i < 6; i++)
			num = num * 10 + tmp.statu[i];	
		if(num == End) {
			ans = tmp.time;
			return true;	
		}

		for(int i = 0; i < 4; i++) {
			int t = 0;
			Dice temp;
			for(int j = 0; j < 6; j++) {
				t = t * 10 + tmp.statu[Z[i][j]];
				temp.statu[j] = tmp.statu[Z[i][j]];
			}
			if(!vis[t]) {
				temp.time = tmp.time + 1;
				q.push(temp);	
				vis[t] = 1;	
			}
		}
	}
	return false;
}

int main() {
	while(scanf("%d", &A[0]) == 1) {
		End = A[0];
		for(int i = 1; i < 6; i++) {
			scanf("%d", &A[i]);
			End = End * 10 + A[i];
		}
		for(int i = 0; i < 6; i++)
			scanf("%d", &B[i]);	
		memset(vis,0,sizeof(vis));
		if(solve()) 
			printf("%d\n",ans);
		else
			printf("-1\n");
	}
	return 0;
}
另一种解法是推出最多旋转几次可以得到所需的情况,可以推出最多旋转5次


#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
const int Z[4][6] = {{2,3,1,0,4,5},{3,2,0,1,4,5},{5,4,2,3,0,1},{4,5,2,3,1,0}};
struct Dice{
	int statu[6], time;
}D;
int A[6], B[6],End, ans;
bool solve() {
	queue<Dice> q;
	for(int i = 0; i < 6; i++)
		D.statu[i] = B[i];
	D.time = 0;
	q.push(D);
	while(!q.empty()) {
		Dice tmp = q.front();
		q.pop();
		int num = 0;
		for(int i = 0; i < 6; i++)
			num = num * 10 + tmp.statu[i];	
		if(num == End) {
			ans = tmp.time;
			return true;	
		}

		for(int i = 0; i < 4; i++) {
			int t = 0;
			Dice temp;
			for(int j = 0; j < 6; j++) {
				t = t * 10 + tmp.statu[Z[i][j]];
				temp.statu[j] = tmp.statu[Z[i][j]];
			}
			temp.time = tmp.time + 1;
			if(temp.time >= 6)
				return false;
			q.push(temp);	
		}
	}
	return false;
}

int main() {
	while(scanf("%d", &A[0]) == 1) {
		End = A[0];
		for(int i = 1; i < 6; i++) {
			scanf("%d", &A[i]);
			End = End * 10 + A[i];
		}
		for(int i = 0; i < 6; i++)
			scanf("%d", &B[i]);	
		if(solve()) 
			printf("%d\n",ans);
		else
			printf("-1\n");
	}
	return 0;
}