您的位置:首页 > 其它

Sicily 1150. 简单魔板[Speical judge]

2013-01-03 19:40 344 查看
/*
使用队列即可处理
注意!char[]转换string时需要增加一位'\0',否则将导致赋值出错,该'\0'不会被计入string的length中
注意!这里的步数是以树的层次来决定的,不是操作的步数
*/
/*
Run Time: 0secs
Run Memory: 312KB
*/

#include <iostream>
#include <string>
#include <set>
#include <queue>

using namespace std;

typedef struct Node{
string node;
string parents;
};

int N;          //要求步数
string dest;    //目标状态

string act[] = {"A", "B", "C"};

//A:上下行互换
string A(string input){
char output[9];
output[0] = input[4];
output[1] = input[5];
output[2] = input[6];
output[3] = input[7];
output[4] = input[0];
output[5] = input[1];
output[6] = input[2];
output[7] = input[3];
output[8] = '\0';

return output;
}

//B:每次以行循环右移一个
string B(string input){
char output[9];
output[0] = input[3];
output[1] = input[0];
output[2] = input[1];
output[3] = input[2];
output[4] = input[7];
output[5] = input[4];
output[6] = input[5];
output[7] = input[6];
output[8] = '\0';

return output;
}

//C:中间四小块顺时针转一格
string C(string input){
char output[9];
output[0] = input[0];
output[1] = input[5];
output[2] = input[1];
output[3] = input[3];
output[4] = input[4];
output[5] = input[6];
output[6] = input[2];
output[7] = input[7];
output[8] = '\0';

return output;
}

Node find(Node sourceNode){
queue<Node> nodeQueue; //节点队列
set<string> used;      //使用过的状态

if(sourceNode.node == dest)
return sourceNode;
nodeQueue.push(sourceNode);
used.insert(sourceNode.node);

while(!nodeQueue.empty()){
Node theNode = nodeQueue.front();    //获取队列头
nodeQueue.pop();

if(theNode.parents.length() >= N){    //超出步数时候退出循环
break;
}

string bufNewNode[3];
bufNewNode[0] = A(theNode.node);
bufNewNode[1] = B(theNode.node);
bufNewNode[2] = C(theNode.node);

for(int i=0; i<3; i++){
Node newNode;
newNode.node = bufNewNode[i];
newNode.parents = theNode.parents + act[i];

if(newNode.node == dest)    //如果找到了目标,则返回结果
return newNode;

if(used.count(newNode.node) == 0){  //不是目标则检查其是否已经看过,否则记录的同时放入队列
used.insert(newNode.node);
nodeQueue.push(newNode);
}
}
}
Node notFound;
notFound.parents = "NotFound";

return notFound;
}

int main()
{
while (cin>>N && (N!=-1)){
char buf[9];
for(int i=0; i<8; i++)
cin >> buf[i];
buf[8] = '\0';
dest = buf;

Node bufNode;
bufNode.node = "12348765";
bufNode.parents = "";

Node destNode = find(bufNode);

if(destNode.parents == "NotFound"){
cout << "-1" << endl;
}else{
cout << destNode.parents.length() << " " << destNode.parents << endl;
}
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: