魔板(广搜与康托展开)

#include<bits/stdc++.h>
using namespace std;
struct node{
    int a[10],pre,step; //魔板上的数字 、已变换步数和其前驱 
    char c;//上一步做的转换 
}lists[400000];//总共只有40000多种排列,所以队列不必开很大
int MS[20];//我们需要转换到的魔板状态
char re[200];//用于输出 
bool hash[50000];//判重数组 
int jc[11]={1,1,2,6,24,120,720,5040,40320,362880};
inline int kt(node tno)//康拓展开
{
    int sum=0;
    for(int i=1;i<=7;i++)
    {
        int t=0;
        for(int j=i+1;j<=8;j++)
        {
            if(tno.a[j]<tno.a[i]) t++;
        }sum+=t*jc[8-i];
    }sum++;
    return sum;
}
node A(node tno){
    node t=tno;
    for(int i=1;i<=4;i++) swap(t.a[i],t.a[9-i]);
    return t;
}
node B(node tno){
    node t=tno;
    t.a[1]=tno.a[4];t.a[8]=t.a[5];
    for(int i=2;i<=4;i++) t.a[i]=tno.a[i-1];
    for(int i=7;i>=5;i--) t.a[i]=tno.a[i+1];
    return t;
}
node C(node tno){
    node t=tno;
    t.a[2]=tno.a[7];t.a[3]=tno.a[2];t.a[6]=tno.a[3];t.a[7]=tno.a[6];
    return t;
}
void print(node tno)
{
    int s=0;
    while(tno.pre!=0)
    {
        re[++s]=tno.c;
//        cout<<re[s]<<endl;
        tno=lists[tno.pre];
    }
    for(int i=s;i>=1;i--){
        printf("%c",re[i]);
    }
    return;//通过反复调用目标节点的前驱进行回溯输出
}
int main()
{
    for(int i=1;i<=8;i++) scanf("%d",&MS[i]);
    for(int i=1;i<=8;i++) lists[1].a[i]=i;
    lists[1].pre=0;
    lists[1].step=0;
    int head=0,tail=1;
    while(head<tail)
    {
        head++;
        bool flag=1;
        for(int i=1;i<=8;i++){
            if(lists[head].a[i]!=MS[i]){
                flag=0;break;
            }
        }
        if(flag)
        {
            printf("%d\n",lists[head].step);
            print(lists[head]);
            return 0;
        }

        for(int i=1;i<=3;i++){
            node k;
            if(i==1) k=A(lists[head]);
            if(i==2) k=B(lists[head]);
            if(i==3) k=C(lists[head]);
            int kk=kt(k);
            if(!hash[kk]){
                hash[kk]=1;
                tail++;
                lists[tail]=k;
                lists[tail].step=lists[head].step+1;
                lists[tail].pre=head;
                lists[tail].c=i-1+'A';
//                cout<<lists[tail].c<<endl;
//                system("pause");
            }
        }
    }    
}

 

转载于:https://www.cnblogs.com/719666a/p/9518587.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值