题目:https://vjudge.net/problem/UVA-253
原解法有误,能够AC但逻辑不对,感谢@林柏陈 的指正。
原思路:如果两骰子有三组相同的相对面,那么两骰子相同。
现思路:模拟骰子的两种旋转方式,用字符串表示状态,通过BFS进行状态空间搜索,set判重。
代码:c++
#include <cstdio>
#include <cstring>
#include <string>
#include <iostream>
#include <algorithm>
#include <set>
#include <queue>
using namespace std;
const int maxn = 20;
const int rotatearr[2][5] = { { 2, 4, 5, 3 },{ 1, 2, 6, 5 } };
char s1[maxn], s2[maxn];
string rotate(string s, int way)
{
string ans(s);
for (int i = 0; i < 3; i++)
{
swap(ans[rotatearr[way][i] - 1], ans[rotatearr[way][i + 1] - 1]);
}
return ans;
}
bool equals(string s)
{
return string(s1 + 1) == s;
}
set<string> st;
bool check()
{
s2[7] = '\0';
string s = string(s2 + 1);
queue<string> q;
q.push(s);
st.insert(s);
while(!q.empty())
{
string cur = q.front();
q.pop();
if(equals(cur))
{
return true;
}
for(int i = 0; i < 2; i++)
{
string t = rotate(cur, i);
if(!st.count(t))
{
st.insert(t);
q.push(t);
}
}
}
return false;
}
int main()
{
while (scanf("%s", s1 + 1) != EOF)
{
st.clear();
for (int i = 7; i <= 12; i++)
{
s2[i - 6] = s1[i];
}
s1[7] = s2[7] = '\0';
printf("%s\n", check() ? "TRUE" : "FALSE");
}
return 0;
}