HDOJ 1430 魔板 (bfs+映射)

题意

对于一个上面4个数下面4个数的魔板,可以如下操作:
A: 上下两行互换
B: 每行循环右移一格
C: 中间4个方块顺时针旋转一格
给你魔板的初始状态与目标状态,请给出由初态到目态变换数最少的变换步骤,若有多种变换方案则取字典序最小的。

思路

在做之前我知道它是一个康拓展开的题,但是在我读题之后感觉直接bfs就可以了啊,一共8!个状态随便过啊= =,然后就超时了。。。
然后发现是我捉急了,这是多组数据的。。。而且题目没说数据组数
不过我觉得不是做法的问题。。。于是bfs预处理一下12345678到全部其他状态的操作,然后就要考虑怎么由任意起点找到操作数。
这个找操作数的方案比较巧妙。。。就是先把原串转化为12345678,记录一下映射的情况,然后目标串也映射一下,那么到新的目标串的操作就是答案了(和那个经典的nlogn求最长公共子序列的方法一样

代码

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define LL long long
#define Lowbit(x) ((x)&(-x))
#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1|1
#define MP(a, b) make_pair(a, b)
const int INF = 0x3f3f3f3f;
const int maxn = 1e6 + 7;
const double eps = 1e-8;
const double PI = acos(-1.0);
string n, m;
map<string, string> ans;

string change(int op, string s)
{
    if (op == 0)
    {
        for (int i = 0; i < 4; i++)
            swap(s[i], s[7-i]);
    }
    else if (op == 1)
    {
        char t = s[3];
        for (int i = 2; i >= 0; i--)
            s[i+1] = s[i];
        s[0] = t;
        t = s[4];
        for (int i = 4; i <= 6; i++)
            s[i] = s[i+1];
        s[7] = t;
    }
    else if (op == 2)
    {
        char t1 = s[1], t2 = s[2];
        char t5 = s[5], t6 = s[6];
        s[1] = t6, s[2] = t1;
        s[5] = t2, s[6] = t5;
    }
    return s;
}

void bfs()
{
    queue<string> q;
    q.push("12345678");
    ans["12345678"] = "";
    while (!q.empty())
    {
        string now = q.front();
        q.pop();
        //cout << now << endl;
        for (int i = 0; i < 3; i++)
        {
            string nxt = change(i, now);
            if (!ans.count(nxt))
            {
                ans[nxt] = ans[now] + (char)('A' + i);
                q.push(nxt);
            }
        }
    }
}

int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    bfs();
    while (cin >> n >> m)
    {
        map<char, char> to;
        for (int i = 0; i < 8; i++)
            to[n[i]] = (char)(i + '1');
        string fun = "";
        for (int i = 0; i < 8; i++)
            fun += to[m[i]];
        cout << ans[fun] << endl;
    }
    return 0;
}
发布了78 篇原创文章 · 获赞 1 · 访问量 6万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章