跳到正文

个人记录

比赛总结

sbl_xh约 5 分钟
原文
文章信息与版本

文章信息

发布
2025年7月12日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 5 分钟

版本

  1. v1当前

P1379 八数码难题

代码:

C++
#include<bits/stdc++.h>
using namespace std;
string st,ed="123804765";
struct node{
    string s;
    int x,step;
};
int adds[4]={1,-1,3,-3};
map<string,bool>mp;
void bfs(){
    int fx = st.find("0");
    mp[st]=1;
    queue<node> q;
    q.push({st,fx,0});
    while(q.size()){
        node p=q.front();
        if(p.s==ed){
            cout << p.step;
            return ;
        }
        
        for(int i = 0;i<4;i++){
            string s = p.s;
            int xx = p.x+adds[i];
            if(xx<0||xx>8) continue;
            if(i==0&&p.x==2) continue;
            if(i==1&&p.x==3) continue;
            if(i==0&&p.x==5) continue;
            if(i==1&&p.x==6) continue;
            
            swap(s[p.x],s[xx]);
            if(mp[s]==0){
                mp[s]=1;
                q.push({s,xx,p.step+1});
            }
        }
        q.pop();
    }

}
int main(){
    cin >> st;
    bfs();
    return 0;
}

P2730 [USACO3.2] 魔板 Magic Squares

代码:

C++
#include<bits/stdc++.h>
using namespace std;
struct node{
    
    string s;
    int step;
    string path;
    
};
string ed;
map<string,bool> mp;
string st;
string changeA(string s){
    swap(s[0],s[7]);swap(s[1],s[6]);swap(s[2],s[5]);swap(s[3],s[4]);
    return s;
}
string changeB(string s){
    swap(s[3],s[2]);
    swap(s[2],s[1]);
    swap(s[1],s[0]);
    swap(s[4],s[5]);
    swap(s[5],s[6]);
    swap(s[6],s[7]);
    return s;
}
string changeC(string s){
    swap(s[2],s[5]);swap(s[2],s[1]);swap(s[1],s[6]);
    return s;
}
int main(){
    ed="12345678";
    for(int i =1;i<=8;i++){
        char c;cin >> c;
        st+=c;
    }
    mp[ed]=1;
    queue<node> q;
    q.push({ed,0,""});
    while(q.size()){
        node f = q.front();
        q.pop();
        if(f.s==st){
            cout << f.step << endl;
            cout << f.path << endl;
        }
        string ss = changeA(f.s);
        if(mp[ss]==0){
            mp[ss]=1;
            q.push({ss,f.step+1,f.path+'A'});
        }
        ss = changeB(f.s);
        if(mp[ss]==0){
            mp[ss]=1;
            q.push({ss,f.step+1,f.path+'B'});
        }
        ss = changeC(f.s);
        if(mp[ss]==0){
            mp[ss]=1;
            q.push({ss,f.step+1,f.path+'C'});
        }
    }
    return 0;
}
原文