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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章