[AcWing 1107] 魔板

image
image
image

BFS + 贪心


点击查看代码
#include<bits/stdc++.h>

using namespace std;

typedef long long LL;

const int N = 1e6 + 10;

string start = "12345678";
map<string,int> d;
map<string, string> path;
int ne[3][8] = {
    {7, 6, 5, 4, 3, 2, 1, 0},
    {3, 0, 1, 2, 5, 6, 7, 4},
    {0, 6, 1, 3, 4, 2, 5, 7},
};

string get(string s, int num)
{
    string res;
    for (int i = 0; i < 8; i ++)
        res += s[ne[num][i]];
    return res;
}

int bfs(string end)
{
    if (start == end)
        return 0;
    queue<string> q;
    q.push(start);
    d[start] = 0;
    while (q.size()) {
        auto t = q.front();
        q.pop();
        for (int i = 0; i < 3; i ++) {
            auto s = get(t, i);
            if (!d.count(s)) {
                q.push(s);
                d[s] = d[t] + 1;
                path[s] += path[t] + char('A' + i);
                if (s == end)
                    return d[end];
            }
        }
    }
    return -1;
}

void solve()
{
    string end;
    for (int i = 0; i < 8; i ++) {
        char c;
        cin >> c;
        end += c;
    }
    int t = bfs(end);
    cout << t << endl;
    if (t > 0)
        cout << path[end] << endl;
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    solve();

    return 0;
}

  1. 贪心
    所要的是字典序最小的操作,所以在进行操作时,优先级为 \(A > B > C\),这样可以保证字典序最小
  2. 三种操作
    可以直接用一个二维数组来记录每种操作之后的字符串下标和原字符串下标的对应关系
  3. 操作序列
    可以直接用 \(map\),最后直接输出 \(end\) 对应的序列
posted @ 2022-08-05 17:30  wKingYu  阅读(29)  评论(0编辑  收藏  举报