算法竞赛入门经典 第二版 习题4-4 骰子涂色 Cube painting uva253

题目: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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值