# hdu1043,3567 Eight 多种解法(A*,双向BFS,康托展开,奇偶剪枝)

传送门

原文链接

与原文稍有不同,用自己的话理解了一遍,代码是自己的

题意描述:经典八数码问题,给定八数码的初始序列,求经过u、r、l、d四种操作到达1 2 3 4 5 6 7 8 x的状态,打印出操作序列?

标签:A*,双向BFS,康托展开,奇偶剪枝

方法一:A* +奇偶剪枝(逆序数)+康拓展开

1、首先移动x时序列(把x除外)的逆序数奇偶性不会发生变化,左右移动序列不变,上下移动每次某个数会向前移动两位或向后移动两位逆序数+2,所以奇偶性不变

2、h(x)估值函数:与目标状态不同的个数,

3、判断是否重复出现可以使用康拓展开

#include<bits/stdc++.h>
using namespace std;
const int max_n  = 4e5+10;
const int dx[4] = {-1,0,1,0};
const int dy[4] = {0,1,0,-1};
const char op[7] ="urdl";


struct node{
    int f,g,h;               //保存 A* 状态的结构体
    int has;
    int m[3][3];
    int x,y;                 //空白格的位置

    bool operator < (node b) const{
        return f == b.f? g>b.g: f > b.f;
    }
};

//估值函数 距离目标状态最少需要几步
int get_h(int m[][3]){
    int res = 0;

    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){
            res += abs((m[i][j] -1)/3 - i) + abs((m[i][j] - 1)%3 - j);
        }
    }

    return res;
}

const int jiecheng[9]={1,1,2,6,24,120,720,5040,40320}; //阶乘

int Cantor(int m[][3]){
    int res  = 0;
    
    //保存到以为数组方便计算
    int tmp[10],cnt = 0;
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){
            tmp[cnt++] = m[i][j];
        }
    }

    //计算康托值
    for(int i = 0; i < 9; i++){
        int k = 0;
        for(int j = i+1; j < 9; j++){
            if(tmp[j] < tmp[i]) k++;
        }
        res+= jiecheng[9-i-1]*k;
    }
    return res;
}

bool vis[max_n];//标记是否在closelist
int par[max_n];//父亲结点
char chr[max_n];//路径记号

//输出路径
void print(int x){
    if(par[x] == -1) return;
    print(par[x]);
    printf("%c",chr[x]);
}
//A*算法
void Astar(node s){
    if(s.has == 0){
        printf("\n");
        return;
    }

    priority_queue<node> qu;
    memset(vis,false,sizeof(vis));
    vis[s.has] = true;
    qu.push(s);
    par[s.has] = -1;

    while(!qu.empty()){
        node v = qu.top() ; qu.pop();

        for(int i = 0; i < 4; i++){//各个方向更新
            int xx = v.x+dx[i], yy = v.y + dy[i];
            if(xx < 0 || yy <0 || xx >= 3 || yy >= 3) continue;

            node u = v;
            swap(u.m[u.x][u.y],u.m[xx][yy]);
            u.has = Cantor(u.m);
            if(vis[u.has]) continue; // 如果访问过 在closelist
            vis[u.has] = true;
            par[u.has] = v.has, chr[u.has] = op[i];//记录路径

            if(u.has == 0){
                print(0);
                printf("\n");
                return;
            }

            u.g++;
            u.h = get_h(u.m);
            u.f = u.g + u.h;
            u.x = xx; u.y = yy;

            qu.push(u);
        }
    }
}
int main(){
    char str[30];
    node s;
    while(gets(str)){
        for(int i = 0,j = 0; j < 9 && str[i] != '\n'; i++){
            if(str[i] == ' ')continue;
            else if(str[i] == 'x') {
                s.m[j/3][j%3] = 9;
                s.x = j/3; s.y = j%3;
            }
            else s.m[j/3][j%3] = str[i]-'0';
            j++;
        }

       s.g = 0; s.h = get_h(s.m); s.f = s.g + s.h;
       s.has = Cantor(s.m);
       //初始化完毕

       int k = 0;                                          //通过逆序数的奇偶判断是否可解
        for(int i= 0; i< 9; i++)
            for(int j= 0; j< i; j++)
                if(s.m[j / 3][j % 3] != 9 && s.m[i / 3][i % 3] < s.m[j / 3][j % 3]) k ++;

        if(k & 1) printf("unsolvable\n");
        else Astar(s);        

    }

    return 0;
}

方法二:BFS逆向打表+康托展开

从1 2 3 4 5 6 7 8 x逆向扩展,记录哪些状态可以到达,以及到达给状态操作

//bfs逆向打表+Canto
#include<bits/stdc++.h>
using namespace std;
const int max_n  = 4e5+10;
const int dx[4] = {-1,0,1,0};
const int dy[4] = {0,1,0,-1};
const char op[7] ="dlur";
bool vis[max_n];//标记是否在closelist
int par[max_n];//父亲结点
char chr[max_n];//路径记号

struct node{
    int m[3][3];
    int has;
    int x,y;
}s,t;


const int jiecheng[9]={1,1,2,6,24,120,720,5040,40320}; //阶乘

int Cantor(int m[][3]){
    int res  = 0;
    
    //保存到以为数组方便计算
    int tmp[10],cnt = 0;
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){
            tmp[cnt++] = m[i][j];
        }
    }

    //计算康托值
    for(int i = 0; i < 9; i++){
        int k = 0;
        for(int j = i+1; j < 9; j++){
            if(tmp[j] < tmp[i]) k++;
        }
        res+= jiecheng[9-i-1]*k;
    }
    return res;
}

void bfs(){

    queue<node> que;
    memset(vis,false,sizeof(vis));
    vis[t.has] = true;

    que.push(t);
    par[t.has] = -1;

    while(!que.empty()){
        node p = que.front(); que.pop();

        for(int i = 0; i < 4; i++){
            int xx = p.x + dx[i], yy = p.y + dy[i];
            if(xx <0 || xx >=3 || yy <0 || yy >= 3 ) continue;

            node u = p;
            swap(u.m[u.x][u.y],u.m[xx][yy]);
            u.has = Cantor(u.m);
            if(vis[u.has]) continue; //访问过

            vis[u.has] = true;
            par[u.has] = p.has;
            chr[u.has] = op[i];
            u.x = xx; u.y = yy;

            que.push(u);
        }
    }
}

void print(int x){
    if(par[x] == -1) return;
    printf("%c",chr[x]);
    print(par[x]);
    
}

int main(){
    char str[30];
    t.m[0][0] = 1; t.m[0][1] = 2; t.m[0][2] = 3;
    t.m[1][0] = 4; t.m[1][1] = 5; t.m[1][2] = 6;
    t.m[2][0] = 7; t.m[2][1] = 8; t.m[2][2] = 9;
    t.has = Cantor(t.m);
    t.x = 2; t.y = 2;
    bfs();
    
    while(gets(str)){
        for(int i = 0,j = 0; j < 9 && str[i] != '\n'; i++){
            if(str[i] == ' ')continue;
            else if(str[i] == 'x') {
                s.m[j/3][j%3] = 9;
                s.x = j/3; s.y = j%3;
            }
            else s.m[j/3][j%3] = str[i]-'0';
            j++;
        }
        s.has = Cantor(s.m);
        //初始化完毕
        if(!vis[s.has]) printf("unsolvable\n");
        else{
            print(s.has);
            printf("\n");
        }
    }


    return 0;
}

方法三:双向BFS+奇偶剪枝+康托展开

//双向bfs + 奇偶剪枝+康托展开
#include<bits/stdc++.h>
using namespace std;
const int max_n  = 4e5+10;
const int dx[4] = {-1,0,1,0};
const int dy[4] = {0,1,0,-1};
const char opz[7] ="urdl";
const char opn[7] = "dlur";

struct node{
    int h;               //保存 A* 状态的结构体
    int has;
    int m[3][3];
    int x,y;                 //空白格的位置
}s,t;



const int jiecheng[9]={1,1,2,6,24,120,720,5040,40320}; //阶乘

int Cantor(int m[][3]){
    int res  = 0;
    
    //保存到以为数组方便计算
    int tmp[10],cnt = 0;
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){
            tmp[cnt++] = m[i][j];
        }
    }

    //计算康托值
    for(int i = 0; i < 9; i++){
        int k = 0;
        for(int j = i+1; j < 9; j++){
            if(tmp[j] < tmp[i]) k++;
        }
        res+= jiecheng[9-i-1]*k;
    }
    return res;
}

bool vis1[max_n],vis2[max_n];//标记是否在closelist
int pre[max_n],nexts[max_n];//父亲结点
char chr1[max_n],chr2[max_n];//路径记号

//输出路径
void print(int x){
    char ans[100];
    int cnt = 0;
    int ch = x;
    while(pre[ch] != -1){
        ans[cnt++] = chr1[ch];
        ch = pre[ch];
    }
    for(int i = cnt-1; i >=0 ;i--){
        printf("%c",ans[i]);
    }
    //printf("\n");
    ch = x;
    while(nexts[ch] != -1){
        printf("%c",chr2[ch]);
        ch = nexts[ch];
    }
    printf("\n");
}
//A*算法
void Astar(node s,node t){
    if(s.has == 0){
        printf("\n");
        return;
    }

    queue<node> qu1,qu2;
    memset(vis1,false,sizeof(vis1));
    memset(vis2,false,sizeof(vis2));
    vis1[s.has] = true;
    vis2[t.has] = true;
    qu1.push(s);
    qu2.push(t);
    pre[s.has] = -1;
    nexts[t.has] = -1;

    int flag ;
    while(!qu1.empty() || !qu2.empty()){
        node v;
        if(!qu1.empty() && (qu2.empty() || qu1.front().h < qu2.front().h)){
            flag = 1; v = qu1.front(); qu1.pop();
            if(vis2[v.has]){
                 print(v.has);
                 return;
            }
        }
        else{
            flag = 2; v = qu2.front(); qu2.pop();
            if(vis1[v.has]) {
                print(v.has); 
                return;
            }
        }
        

        for(int i = 0; i < 4; i++){//各个方向更新
            int xx = v.x+dx[i], yy = v.y + dy[i];
            if(xx < 0 || yy <0 || xx >= 3 || yy >= 3) continue;

            node u = v;
            swap(u.m[u.x][u.y],u.m[xx][yy]);
            u.has = Cantor(u.m);
            u.h = v.h +1;
            u.x = xx; u.y = yy;

            if(flag == 1 && !vis1[u.has]){
                pre[u.has] = v.has;
                chr1[u.has] = opz[i];  
                if(vis2[u.has]){

                    print(u.has);
                    return;
                }
                
                vis1[u.has] = true;
                qu1.push(u)  ;
            }
            else if( flag == 2 && !vis2[u.has]) {  
                nexts[u.has] = v.has;
                chr2[u.has] = opn[i];
                if(vis1[u.has]){
                    
                    print(u.has);
                    return;
                }
                
                vis2[u.has] = true;
                qu2.push(u);
            }
        }
    }
    printf("unsolvable\n");
}
int main(){
    char str[30];
    t.m[0][0] = 1; t.m[0][1] = 2; t.m[0][2] = 3;
    t.m[1][0] = 4; t.m[1][1] = 5; t.m[1][2] = 6;
    t.m[2][0] = 7; t.m[2][1] = 8; t.m[2][2] = 9;
    t.has = Cantor(t.m);
    t.x = 2; t.y = 2;t.h = 0;

    while(gets(str)){
        for(int i = 0,j = 0; j < 9 && str[i] != '\n'; i++){
            if(str[i] == ' ')continue;
            else if(str[i] == 'x') {
                s.m[j/3][j%3] = 9;
                s.x = j/3; s.y = j%3;
            }
            else s.m[j/3][j%3] = str[i]-'0';
            j++;
        }

        s.h = 0;
        s.has = Cantor(s.m);
       //初始化完毕

       int k = 0;                                          //通过逆序数的奇偶判断是否可解
        for(int i= 0; i< 9; i++)
            for(int j= 0; j< i; j++)
                if(s.m[j / 3][j % 3] != 9 && s.m[i / 3][i % 3] < s.m[j / 3][j % 3]) k ++;

        if(k & 1) printf("unsolvable\n");
        else Astar(s,t);        

    }

    return 0;
}

hdu3567 进阶版

映射+bfs打表+康托展开

按照X的位置分成了九种大类,我们就可以做这样的一个映射“12X345678”

分别是:1 → 1,2 → 2,X → X,4 → 3,5 → 4,3 → 5,7 → 6,8 → 7,6 → 8,

然后目标状态一样要映射掉。

为了使得字典序最小我们必须要让方向以 d l r u   ( d o w n , l e f t , r i g h t , u p ) dlru\,(down,left,right,up) dlru(downleftrightup)的顺序进行bfs(字母顺序),这样我们预处理完记录下路径后,我们只能从得到的目标状态往前找到初始状态,然后在逆序输出。

//bfs向打表+Canto
#include<bits/stdc++.h>
using namespace std;
const int max_n  = 4e5+10;

const char op[7] ="dlru";
const int dx[4] = {1,0,0,-1};
const int dy[4] = {0,-1,1,0};

bool vis[9][max_n];//标记是否在closelist
int par[9][max_n];//父亲结点
char chr[9][max_n];//路径记号
int yin[10],cas;

struct node{
    int m[3][3];
    int has;
    int x,y;
};

char Eight[9][10] ={ "X12345678","1X2345678","12X345678","123X45678","1234X5678","12345X678",
                         "123456X78","1234567X8","12345678X"};

const int jiecheng[9]={1,1,2,6,24,120,720,5040,40320}; //阶乘

int Cantor(int m[][3]){
    int res  = 0;
    
    //保存到以为数组方便计算
    int tmp[10],cnt = 0;
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){
            tmp[cnt++] = m[i][j];
        }
    }

    //计算康托值
    for(int i = 0; i < 9; i++){
        int k = 0;
        for(int j = i+1; j < 9; j++){
            if(tmp[j] < tmp[i]) k++;
        }
        res+= jiecheng[9-i-1]*k;
    }
    return res;
}

void bfs(node v,int kind){

    queue<node> que;
    vis[kind][v.has] = true;

    que.push(v);
    par[kind][v.has] = -1;

    while(!que.empty()){
        node p = que.front(); que.pop();

        for(int i = 0; i < 4; i++){
            int xx = p.x + dx[i], yy = p.y + dy[i];
            if(xx <0 || xx >=3 || yy <0 || yy >= 3 ) continue;

            node u = p;
            swap(u.m[u.x][u.y],u.m[xx][yy]);
            u.has = Cantor(u.m);
            if(vis[kind][u.has]) continue; //访问过

            vis[kind][u.has] = true;
            par[kind][u.has] = p.has;
            chr[kind][u.has] = op[i];
            u.x = xx; u.y = yy;

            que.push(u);
        }
    }
}

void print(int x,int kind){
    int ans = 0;
    char res[100];
    while(x != -1){
        res[ans++] = chr[kind][x];
        x = par[kind][x];

    }
    printf("Case %d: %d\n",++cas,ans-1);
    for(int i = ans-2; i >= 0; i--){
        printf("%c",res[i]);
    }
    printf("\n");
    
}
void init(char *s,int kind){

    node v;
    int cnt = 0;
    for(int i = 0; i < 9; i++){
        int x = i/3, y = i%3;
        if(s[i] == 'X'){
            v.m[x][y] = 9;
            v.x = x; v.y = y;
        }
        else v.m[x][y] = s[i]-'0';
    }
    v.has = Cantor(v.m);

    bfs(v,kind);
}

int main(){
    char str1[30],str2[30];
    int T;
    cas = 0;
    scanf("%d",&T);
    char ch;scanf("%c",&ch);
    
    memset(vis,false,sizeof(vis));
    memset(par,-1,sizeof(par));
    for(int i = 0; i < 9; i++){
        init(Eight[i],i);
    }
    
    while(T--){
        node s;
        memset(yin,0,sizeof(yin));
        int kind,cnt = 1;

        gets(str1);
        gets(str2);
        for(int i = 0;i < 9; i++){
            if(str1[i] == 'X') {
                kind = i;
                yin[9] = 9;
            }
            else {
                yin[str1[i]-'0'] = cnt++;
            }
           
        }
        for(int i = 0; i < 9; i++){
            int x = i/3, y = i%3;
            if(str2[i] == 'X')s.m[x][y] = yin[9];
            else s.m[x][y] = yin[str2[i]-'0'];
        }
       
        s.has = Cantor(s.m);

       //初始化完毕      
      
        print(s.has,kind);
    
    }

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值