魔板

来源:互联网 发布:南方周末 知乎 编辑:程序博客网 时间:2024/05/16 09:43


Description

在魔方风靡全球之后不久,Rubik先生发明了它的简化版――魔板。魔板由8个同样大小的方块组成,每个方块颜色均不相同,可用数字1-8分别表示。任一时刻魔板的状态可用方块的颜色序列表示:从魔板的左上角开始,按顺时针方向依次写下各方块的颜色代号,所得到的数字序列即可表示此时魔板的状态。例如,序列(1,2,3,4,5,6,7,8)表示魔板状态为:

1 2 3 4
8 7 6 5

对于魔板,可施加三种不同的操作,具体操作方法如下:

A: 上下两行互换,如上图可变换为状态87654321
B: 每行同时循环右移一格,如上图可变换为41236785
C: 中间4个方块顺时针旋转一格,如上图可变换为17245368

给你魔板的初始状态与目标状态,请给出由初态到目态变换数最少的变换步骤,若有多种变换方案则取字典序最小的那种。
 

Input

每组测试数据包括两行,分别代表魔板的初态与目态。
 

Output

对每组测试数据输出满足题意的变换步骤。

Sample Input

12345678
17245368
12345678
82754631  

Sample Output

C
AC  
map +一个bfs 打表,映射位置
代码如下:
值得总结
//
// Create by Running Photon on 2015-03-08
//
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <iomanip>
#include <algorithm>
#include <cctype>
#include <stack>
#include <queue>
#include <map>
#include <string>
#include <set>
#include <vector>
using namespace std;
#define CLR(x) memset(x,0,sizeof x)
#define ll long long
const int inf=0x3f3f3f3f;
const int maxn=1e5+5;
const int MOD=5e5+5;
map <string, string> mp;
typedef pair <string, string> pa;
string st, ed;
void fun(int jud, string& ss)
{
    if(jud == 0){
        reverse(ss.begin(), ss.end());
    }
    else if(jud == 1){
        for(int i = 3; i > 0; i--) swap(ss[i], ss[i-1]);
       for(int i = 4; i < 7; i++) swap(ss[i], ss[i+1]);
    }
    else{
        char x = ss[1];
  swap(x, ss[2]); swap(x, ss[5]); swap(x, ss[6]); swap(x, ss[1]);
    }
}
void bfs()
{
    queue <pa> que;
    mp["12345678"] = "";
    que.push(pa("12345678", ""));
    while(!que.empty()){
        string s = que.front().first;
        string cur = que.front().second;
        que.pop();
        for(int i = 0; i < 3; i++){
            string ns = s;
            char tmp = i + 'A';
            fun(i, ns);
            if(!mp.count(ns)){
                mp[ns] = mp[s] + tmp;
                //cout << ns << endl;
                que.push(pa(ns, mp[ns]));
            }
        }
    }
}
int main()
{
#ifdef LOCAL
 freopen("in.txt","r",stdin);
 //freopen("out.txt","w",stdout);
#endif
 ios_base::sync_with_stdio(0);
 bfs();
 while(cin >> st >> ed){
        char a[10];
        for(int i = 0; i < 8; i++) a[st[i] - '0'] = i + '1';
        for(int i = 0; i < 8; i++) ed[i]= a[ed[i] - '0'];
        cout << mp[ed] <<endl;
 }
 return 0;
}
0 0
原创粉丝点击