hdu 1043 八数码 单向广搜

从目标解开始广搜,就是打表,记录所有可以到目标解的路径,在HDU很容易超空间。

传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1043

#include <iostream>
#include <algorithm>
#include <queue>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

int ctarray[10] ={1,1,2,6,24,120,720,5040,40320,362880};
int vis[400005];

int ct(int * a){
    int i,j,con,ans=0;
    for(i=0;i<8;i++){
        con = 0;
        for(j=i+1;j<9;j++){
            if(a[j]<a[i]){
                con ++;
            }
        }
        ans += con * ctarray[8-i];
    }
    return ans;
}

typedef struct L{
    int a[10];
    int p,pos;
    string step;
}L;

string d = "udlr";

int dirtx[4] = {1,-1,0,0};
int dirty[4] = {0,0,1,-1};
int xx,yy;

string zans[400005];

void bfs(){
    queue<L>q;
    int i;
    L now,next;
    memset(vis,0,sizeof(vis));
    for(i=0;i<8;i++){
        now.a[i] = i + 1;
    }
    now.a[8] = 0;
    now.p = ct(now.a);
    now.pos = 8;
    now.step = "";
    q.push(now);
    vis[now.p] = 1;
    zans[now.p] ="";
    while(!q.empty()){
        now  = q.front();
        q.pop();
        for(i=0;i<4;i++){
            xx = now.pos/3 + dirtx[i];
            yy = now.pos%3 + dirty[i];
            if(xx<0||xx>2||yy<0||yy>2)continue;
            next = now;
            next.pos = xx*3 + yy ;
            next.a[now.pos] = next.a[next.pos];
            next.a[next.pos] = 0;
            next.p = ct(next.a);
            if(!vis[next.p]){
                next.step += d[i];
                vis[next.p] = 1;
                zans[next.p] = next.step;
                q.push(next);
            }
        }
    }
}

void pt(int * a){
    int tt = ct(a);
    if(!vis[tt]){
        puts("unsolvable");
        return;
    }
    for(int i=zans[tt].length()-1;i>=0;i--){
        printf("%c",zans[tt][i]);
    }
    puts("");
}

int main(void){
    //freopen("a.in","r",stdin);
    bfs();
    char tempa[100];
    int i,t[10],k;
    while(gets(tempa)){
        k = 0;
        for(i=0;i<strlen(tempa);i++){
            if(tempa[i]>='0'&&tempa[i]<='9'){
                t[k++] = tempa[i] - '0';
            }
            if(tempa[i]=='x'){
                t[k++] = 0;
            }
        }
        pt(t);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值