题目链接:http://codeup.cn/problem.php?cid=100000609&pid=3
思路就不写了
我的代码
#include<iostream>
#include<queue>
#include<unordered_map>
#include<stack>
#include<cstring>
using namespace std;
// 某时刻的状态为整数
int source = 12345678;
int target;
const int maxn = 4000000; // 4 1e5
// 当前状态
struct Node {
int station;
int step;
int op; // way
int pre;
} q[maxn];
Node dosomething(Node node, int head, int way) {
Node newNode;
// station
char cur[9];
int temp_num = node.station;
sprintf(cur, "%d", temp_num);
if (way == 1) { //A 34 25 16 07
int index1 = 3;
int index2 = 4;
for (int i = 0; i < 4; i++) {
swap(cur[index1 - i], cur[index2 + i]);
}
}
if (way == 2) { //B
char temp1 = cur[3], temp2 = cur[4];
for (int i = 3; i >= 1; i--) {
cur[i] = cur[i - 1];
}
for (int i = 4; i <= 6; i++) {
cur[i] = cur[i + 1];
}
cur[0] = temp1;
cur[7] = temp2;
}
if (way == 3) { //C 0开始 2 = 1 5 = 2 6 = 5 1 = 6
char temp = cur[2];
cur[2] = cur[1];
cur[1] = cur[6];
cur[6] = cur[5];
cur[5] = temp;
}
int newNum;
sscanf(cur, "%d", &newNum);
newNode.station = newNum;
// step;
newNode.step = ++node.step;
// op
newNode.op = way;
// pre
newNode.pre = head;
return newNode;
}
unordered_map<int, int>mp; // bool默认初始值false;
int head = 0;
int tail = 1;
Node BFS(Node st) {
mp.clear();
memset(q, 0, sizeof(q));
q[head] = st;
mp[q[head].station] = 1;
while (head != tail) {
Node top = q[head];
if (top.station == target)
return top;
for (int way = 1; way <= 3; way++) {
Node newNode = dosomething(top, head, way);
if (mp.count(newNode.station) == 0) {
q[tail++] = newNode;
mp[newNode.station] = 1;
}
}
head++;
}
return { 0,0,0,-1 };
}
stack<int> s;
void myPrint(Node node) {
printf("%d\n", node.step);
while (!s.empty()) {
s.pop();
}
if (node.step==0)
{
printf(" \n");
return;
}
s.push(node.op);
int index = node.pre;
while (index != 0) {
s.push(q[index].op);
index = q[index].pre;
}
int top;
string ans;
while (!s.empty()) {
top = s.top();
s.pop();
// printf("%c", top - 1 + 'A');
ans += top - 1 + 'A';
}
int len = ans.length();
for (int i = 0; i <len; i++)
{
if (i%60==0&&i)
printf("\n");
printf("%c",ans[i]);
}
printf("\n");
}
int main() {
char a[20];
while(gets(a)!=NULL) {
char target1[10];
int indexT = 0 ;
for (int i = 0; i < 20; i++) {
if (a[i]<='9'&&a[i]>='0') {
target1[indexT++] = a[i];
}
}
sscanf(target1, "%d", &target);
// 初始step = 0
Node st = { source, 0,0,-1 };
myPrint(BFS(st));
}
return 0;
}
吐槽
这个代码死活就是
答案错误88
,检查了很久没检查出来
直到我把某一项操作修改
int len = ans.length();
for (int i = 0; i <len; i++)
{
if (i%60==0&&i)
printf("\n");
printf("%c",ans[i]);
}
printf("\n");
中的
改成
或者
竟然通过了!通过了!
奇怪的知识增加了
若是有小伙伴清楚原因,麻烦在评论区告知,嘻嘻