悬赏关注,想不明白哪里有问题
查看原帖
悬赏关注,想不明白哪里有问题
784813
SakurajiamaMai楼主2023/5/14 19:47
#include<bits/stdc++.h>
using namespace std;
string st,ed;
int g[3][5];
char op[]="ABC";
unordered_map<string,int>dist;
unordered_map<string,string>pre;
string move0(string s)
{
    for(int i=0;i<4;i++)
        swap(s[i+4],s[i]);
    return s;
}
string move1(string s)
{
    char tmp1=s[3],tmp2=s[7];
    s[3]=s[2],s[7]=s[6];
    s[2]=s[1],s[6]=s[5];
    s[1]=s[0],s[5]=s[4];
    s[0]=tmp1,s[4]=tmp2;
    return s;
}
string move2(string s)
{
    swap(s[1],s[2]);
    swap(s[1],s[6]);
    swap(s[1],s[5]);
    return s;
}
void bfs()
{
    queue<string>que;
    que.push(st);
    dist[st]=0;
    while(!que.empty())
    {
        string now=que.front();
        que.pop();
        if(now==ed) return;
        string m[3];
        m[0]=move0(now),m[1]=move1(now),m[2]=move2(now);
        for(int i=0;i<3;i++)
        {
            string k=m[i];
            if(!dist.count(k))
            {
                dist[k]=i;
                pre[k]=now;
                que.push(k);
            }
        }
    }
    return;
}
int main()
{
    for(int i=0;i<8;i++)
    {
        char c;
        cin>>c;
        ed+=c;
    }
    st="12345678";
    bfs();
    int k=0;
    string res;
    while(ed!=st)
    {
        k++;
        res=res+op[dist[ed]];
        ed=pre[ed];
    }
    cout<<k<<endl;
    reverse(res.begin(),res.end());
    cout<<res<<endl;
    return 0;
}
2023/5/14 19:47
加载中...