蒟蒻八数码RE求助
查看原帖
蒟蒻八数码RE求助
305121
8atemak1r楼主2022/2/5 16:09

除了最后一个点全RE,先判的越界再进队的(需要加注释的话@我一下就好了)

#include<iostream>
#include<queue>
using namespace std;
char c[10];
int en[10] = {0, 1, 2, 3, 8, 0, 4, 7, 6, 5}, ans = 92919;
bool vis[400000];
struct node{
    int n[15], stp, pos;
    bool operator < (const node &a) const {
        int atmp = 0, tmp = 0;
        for(int i = 1; i <= 9; ++ i) {
            if(a.n[i] != en[i]) ++ atmp;
            if(n[i] != en[i]) ++ tmp;
        }
        return atmp < tmp;
    }
}s, t;
int fac[10] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};
int cantor(int x[]){
    int res = 0;
    bool flag[10] = {};
    for(int i = 1; i <= 9; ++ i) {
        int app = 0;
        for(int j = 0; j < 9; ++ j) 
            if(flag[j] == 0 && j <= x[i]) ++ app; 
        res += app * fac[9 - i]; flag[x[i]] = 1;
    }
    return res;
}
inline void swap(int &p, int &q) {p ^= q ^= p ^= q;}
queue<node> q;
int cnt[4] = {1, -1, 3, -3};
void bfs() {
    q.push(s);
    while(!q.empty()) {
        node tmp = q.front(), nxt; q.pop();
        if(cantor(tmp.n) == ans) {
            cout << tmp.stp;
            exit(0);
        }
        for(int i = 0; i < 4; ++ i) {
            nxt = tmp;
            if(tmp.pos + cnt[i] > 0 && tmp.pos + cnt[i] <= 9) {
                swap(nxt.n[tmp.pos], nxt.n[tmp.pos + cnt[i]]);
                if(vis[cantor(nxt.n)] == false) {
                    nxt.pos = nxt.pos + cnt[i];
                    nxt.stp = tmp.stp + 1;
                    q.push(nxt);
                    vis[cantor(nxt.n)] = true;
                }
            }
        }
    }
}
int main() {
    cin >> c;
    for(int i = 0; i < 9; ++ i) {
        s.n[i + 1] = (int)(c[i] - '0');
    }
    s.stp = 0;
    for(int i = 1; i <= 9; ++ i) {
        if(s.n[i] == 0) {
            s.pos = i;
            break;
        }
    }
    vis[cantor(s.n)] = true;
    bfs();
    return 0;
}
2022/2/5 16:09
加载中...