奥赛一本通 1449 魔板

1449 魔板

题目大意

包含 8 个格子的魔板,有 3 种操作规则可以交换上面的若干格子,求达到目标状态需要的最少操作次数。

知识要点

广度优先搜索、状态压缩

解题思路

将魔板的状态存储为八进制数,利用常量数组模拟每种操作规则。为了得到最终的操作方案,还需要为每个状态存储它的上一个状态。

参考代码

#include <bits/stdc++.h>
using namespace std;

bool v[076543211]; //状态标记(八进制写法)
char g[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}
};
struct {int x, pre, op;} Q[40320]; //数组模拟队列
int BFS(int t) {
    int x = 012345670, y, tmp[8];
    Q[0] = {x, 0, 0}, v[x] = 1;

    for(int head = 0, tail = 1; head != tail; head++) {
        x = Q[head].x;
        for(int j = 7; j >= 0; j--) tmp[j] = x % 8, x /= 8;
        for(int i = 0; i < 3; i++) {
            y = 0;
            for(int j = 0; j < 8; j++) y = y * 8 + tmp[g[i][j]];
            if(v[y]) continue;
            Q[tail++] = {y, head, i}, v[y] = 1;
            if(y == t) return tail - 1; //返回状态所在位置
        }
    }
    return 0;
}
int main() {
    int s, t = 0;
    for(int i = 0; i < 8; i++) scanf("%d", &s), t = t * 8 + s % 8;
    if(t == 012345670) return puts("0");

    s = BFS(t);
    int cnt = 0, ans[30];
    while(s > 0) ans[cnt++] = Q[s].op, s = Q[s].pre; //持续找上一状态
    printf("%d\n", cnt);
    while(cnt--) putchar(ans[cnt] + 'A');
    return 0;
}
posted @ 2026-09-15 16:53  萧西待水  阅读(22)  评论(0)    收藏  举报