1150. 简单魔板
来源:互联网 发布:root软件 编辑:程序博客网 时间:2024/05/01 20:57
/*1150. 简单魔板初始状态1 2 3 4 8 7 6 5给定一个状态,在指定步骤内通过A、B、C操作到达目标态定义一个状态数组,头指针fp指向当前的父节点操作,rp指向子节点操作。判断是否加入子节点序列时:判重! 扫描整个数组,若出现重复状态则跳过,对每个父节点都有三个操作,符合条件的进入队列,rp依次后移,fp完成三个操作后也fp++ */#include <stdlib.h>#include <iostream>using namespace std;struct state{ int x; int y; int pre; char op; };void OPA(int &x, int &y){ int temp = y; y = x; x = temp; }void OPB(int &x, int &y){ x = x%10 * 1000 + x/10; y = y%10 * 1000 + y/10; }void OPC(int &x, int &y){ int x1 = x/1000; int x2 = (x - x1*1000)/100; int x3 = (x - x1*1000 - x2*100)/10; int x4 = x - x1*1000 - x2*100 - x3*10; int y1 = y/1000; int y2 = (y - y1*1000)/100; int y3 = (y - y1*1000 - y2*100)/10; int y4 = y - y1*1000 - y2*100 - y3*10; x = x1*1000 + y2*100 + x2*10 + x4; y = y1*1000 + y3*100 + x3*10 + y4;}int main(){ int n; int x, y; int x1,x2,x3,x4, y1,y2,y3,y4; state qm[81000]; char opresult[300]; n = 0; char op[3] = {'A', 'B', 'C'}; while(cin >> n && n != -1){ cin >> x1 >> x2 >> x3 >> x4 >> y1 >> y2 >> y3 >> y4; x = x1*1000+x2*100+x3*10+ x4; y = y1*1000+y2*100+y3*10+ y4; //cout << x << endl << y; int tempx; int tempy; int fp=0; int rp=1; state init = {1234, 8765, -1, '-'}; qm[0] = init; bool flag = true; while(flag){ tempx = qm[fp].x; tempy = qm[fp].y; //cout << tempx << " " << tempy << endl; for(int i=0; i<3 && flag; i++){ tempx = qm[fp].x; tempy = qm[fp].y; if(op[i] == 'A') { OPA(tempx, tempy); //cout << op[i] << tempx << endl << tempy << endl; } if(op[i] == 'B') { OPB(tempx, tempy); //cout << op[i] << tempx << endl << tempy << endl; } if(op[i] == 'C') { OPC(tempx, tempy); //cout << op[i] << tempx << endl << tempy << endl; } state temp = { tempx, tempy, fp,op[i]}; if(tempx == x && tempy == y){ flag = false; qm[rp] = temp; rp++; } else { bool isExist = false; for(int k=0; k<rp; k++) if(qm[k].x == tempx && qm[k].y == tempy) { isExist = true; break; } if(!isExist){ qm[rp] = temp; rp++; } } } fp++; // cout << fp << endl; } //cout << rp << endl; int i = 0; int temppre=rp-1; while(qm[temppre].pre!= -1) { opresult[i] = qm[temppre].op; //cout << temppre << endl; temppre = qm[temppre].pre; i++; if(i>300) { cout << -1; break; } } if(i<=300) { cout << i << " " ; for(int j=i-1; j>=0; j--) cout << opresult[j]; } cout << endl; } system("pause"); return 0;}