搜索进阶-----B - Eight II

Eight-puzzle, which is also called “Nine grids”, comes from an old game.

In this game, you are given a 3 by 3 board and 8 tiles. The tiles are numbered from 1 to 8 and each covers a grid. As you see, there is a blank grid which can be represented as an ‘X’. Tiles in grids having a common edge with the blank grid can be moved into that blank grid. This operation leads to an exchange of ‘X’ with one tile.

We use the symbol ‘r’ to represent exchanging ‘X’ with the tile on its right side, and ‘l’ for the left side, ‘u’ for the one above it, ‘d’ for the one below it.

A state of the board can be represented by a string S using the rule showed below.

The problem is to operate an operation list of ‘r’, ‘u’, ‘l’, ‘d’ to turn the state of the board from state A to state B. You are required to find the result which meets the following constrains:

  1. It is of minimum length among all possible solutions.
  2. It is the lexicographically smallest one of all solutions of minimum length.
    Input
    The first line is T (T <= 200), which means the number of test cases of this problem.

The input of each test case consists of two lines with state A occupying the first line and state B on the second line.
It is guaranteed that there is an available solution from state A to B.
Output
For each test case two lines are expected.

The first line is in the format of “Case x: d”, in which x is the case number counted from one, d is the minimum length of operation list you need to turn A to B.
S is the operation list meeting the constraints and it should be showed on the second line.
Sample Input
2
12X453786
12345678X
564178X23
7568X4123
Sample Output
Case 1: 2
dd
Case 2: 8
urrulldr

这道题真的是惊了,直接bfs必然超时,用map还会超空间,本来想用map<int,string>记录路径,但是字符串操作会超时,还会超空间。。。。
太菜了,不会,只能去网上查题解
两种做法:
1>预处理 + 康托展开

按照X的位置分成了九种大类,那么其他情况该怎么办呢,我们可以通过映射,把初始状态根据X的位置映射到上面其中的一种(一定可以找到一种),然后根据初始数组每个数字所映射的数字,去更新目标数组的数字这样就可以从以上九种状态中找了,比如说示例1中的12X453786我们就可以做这样的一个映射“12X345678”分别是:1 → 1,2 → 2,X → X,4 → 3,5 → 4,3 → 5,7 → 6,8 → 7,6 → 8,然后目标状态一样要映射掉。这样我们就可以通过预处理,将以每种状态为起点状态开始bfs存下它所能到达的所有状态的路径,但是这个题还有个特殊要求要求长度最短,字典序最小,那么记录路径就不能想上个题一样直接方向和字符相反对应了。

为了使得字典序最小我们必须要让方向以dlru(down,left,right,up)的顺序进行bfs(字母顺序),这样bfs出来的路径自然是最短的和字典顺序最小的

2>双向bfs+康托展开
(我写的时候一直wa。。。。)
按照上一个解法那样记录路径时不可以的,这样找不到终止状态到某个状态的字典序最小的路径,所以需要存储下来路径进行比较,但是这样空间会爆,所以按网上的做法是转换成四进制存储,0,1,2,3代表d,l,r,u。
在每次还要判断一下,如果路径长度更小,则将之更新
注意:四进制路径要用long long ,否则会超

方法一、

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
#include<queue>
using namespace std;
typedef long long LL;
const int inf = 0x3f3f3f3f;
const int N = 4e5;

char ptr[] = "dlru";
int vis[10][N];
int pre[10][N];
char s[10];
char t[10];
int col[5] = {1,0,0,-1};
int con[5] = {0,-1,1,0};

bool judge(int i,int j)
{
    if(i < 0 || j < 0)
        return false;
    if(i >= 3 || j >= 3)
        return false;
    return true;
}

static const int FAC[] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};   // 阶乘
int cantor(int *a, int n)
{
    int x = 0;
    for (int i = 0; i < n; ++i) {
        int smaller = 0;  // 在当前位之后小于其的个数
        for (int j = i + 1; j < n; ++j) {
            if (a[j] < a[i])
                smaller++;
        }
        x += FAC[n - i - 1] * smaller; // 康托展开累加
    }
    return x;  // 康托展开值
}

typedef struct Node{
    int num[10];
    int sta;
    int pos;
    Node(int *a,int x,int y){
        for(int i = 0;i < 9;++i)
            num[i] = a[i];
        sta = x;
        pos = y;
    }
}Node;

void bfs(Node node,int pos)
{
    queue<Node>que;
    que.push(node);
    vis[pos][node.sta] = 0;
    while(!que.empty())
    {
        Node tmp = que.front();
        que.pop();
        int x = tmp.pos / 3,y = tmp.pos % 3;
        for(int i = 0;i < 4;++i)
        {
            int x1 = x + col[i];
            int y1 = y + con[i];
            if(judge(x1,y1)){
                Node u = tmp;
                swap(u.num[tmp.pos],u.num[x1 * 3 + y1]);
                int ans = cantor(u.num,9);
                if(vis[pos][ans] == -1){
                    vis[pos][ans] = i;
                    pre[pos][ans] = u.sta;
                    u.pos = x1 * 3 + y1;
                    u.sta = ans;
                    que.push(u);
                }
            }
        }
    }
}

void init()
{
    memset(vis,-1,sizeof(vis));
    memset(pre,-1,sizeof(pre));
    int a[10];
    for(int i = 0;i < 9;++i)
    {
        int p = 0;
        a[i] = 0;
        for(int j = 0;j < 9;++j){
            if(j != i){
                a[j] = ++p;
            }
        }
        int x = cantor(a,9);
        bfs((Node){a,x,i},i);
    }
}

int main()
{
    init();
    int k;
    scanf("%d",&k);
    int cnt = 0;
    while(k--)
    {
        cnt++;
        scanf("%s",s);
        scanf("%s",t);
        int ss,st;
        for(int i = 0;i < 9;++i)
        {
            if(s[i] == 'X') ss = i;
            if(t[i] == 'X') st = i;
        }
        int num[10];
        int c[10];
        int p = 1;
        for(int i = 0;i < 9;++i){
            if(i != ss){
                c[s[i] - '0'] = p++;
            }
        }
        for(int i = 0;i < 9;++i){
            if(i != st){
                num[i] = c[t[i] - '0'];
            }else{
                num[i] = 0;
            }
            //cout << num[i] << endl;
        }
        int sta = cantor(num,9);
        string xx;
        while(sta != -1)
        {
            xx += ptr[vis[ss][sta]];
            sta = pre[ss][sta];
        }
        printf("Case %d: %d\n",cnt,xx.size() - 1);
        int len = xx.size() - 1;
        for(int i = len - 1;i >= 0;--i)
        {
            printf("%c",xx[i]);
        }
        printf("\n");
    }
    return 0;
}

方法二、

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<map>
#include<queue>
using namespace std;
typedef long long LL;
const int inf = 0x3f3f3f3f;
const int N = 4e5;

char ptr[] = "dlru";
int vis[2][N];
LL dp[2][N];
char s[10];
char t[10];
int col[5] = {1,0,0,-1};
int con[5] = {0,-1,1,0};
int dd[2][4] = {{0,1,2,3},{3,2,1,0}};
LL mm[30];

bool judge(int i,int j)
{
    if(i < 0 || j < 0)
        return false;
    if(i >= 3 || j >= 3)
        return false;
    return true;
}

static const int FAC[] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};   // 阶乘
int cantor(int *a, int n)
{
    int x = 0;
    for (int i = 0; i < n; ++i) {
        int smaller = 0;  // 在当前位之后小于其的个数
        for (int j = i + 1; j < n; ++j) {
            if (a[j] < a[i])
                smaller++;
        }
        x += FAC[n - i - 1] * smaller; // 康托展开累加
    }
    return x;  // 康托展开值
}

typedef struct Node{
    int num[10];
    int sta;
    int pos;
    int flag;
    int step;
    LL path;
    Node(int *a,int x,int y,int z,int m,int n){
        for(int i = 0;i < 9;++i)
            num[i] = a[i];
        sta = x;pos = y;flag = z;step = m;path = n;
    }
}Node;

string getstr(LL path,int flag,int ans)
{
    int a[100];
    int k = 0;
    for(int i = 0;i < vis[flag][ans];++i)
    {
        a[k++] = path % 4;
        path /= 4;
    }
    string s;
    for(int i = k - 1;i >= 0;--i)
        s += ptr[a[i]];
    return s;
}

void bfs(Node ss,Node st)
{
    memset(vis,-1,sizeof(vis));
    queue<Node>que;
    vis[0][ss.sta] = 0;
    vis[1][st.sta] = 0;
    if(ss.sta == st.sta){
        printf("0\n\n");
        return ;
    }
    que.push(ss);
    que.push(st);
    int MIN = inf;
    string res;
    while(!que.empty())
    {
        Node tmp = que.front();
        que.pop();
        int x = tmp.pos / 3,y = tmp.pos % 3;
        for(int i = 0;i < 4;++i)
        {
            Node u = tmp;
            int x1 = x + col[i],y1 = y + con[i];
            if(judge(x1,y1)){
                u.pos = x1 * 3 + y1;
                swap(u.num[tmp.pos],u.num[u.pos]);
                int k = cantor(u.num,9);
                u.sta = k;
                LL ans;
                if(vis[u.flag][k] != -1)
                {
                    if(u.step + 1 > vis[u.flag][k]) continue;
                    else{
                        if(u.flag) ans = dd[u.flag][i] * mm[u.step] + u.path;
                        else ans = u.path * 4 + dd[u.flag][i];
                        if(dp[u.flag][k] > ans)
                            dp[u.flag][k] = ans;
                    }
                }else{
                    vis[u.flag][k] = u.step + 1;
                    if(u.flag) dp[u.flag][k] = dd[u.flag][i] * mm[u.step] + u.path;
                    else dp[u.flag][k] = u.path * 4 + dd[u.flag][i];
                }
                u.step++;
                u.path = dp[u.flag][k];
                if(vis[1 - u.flag][k] != -1)
                {
                    string s = getstr(dp[0][k],0,k) + getstr(dp[1][k],1,k);
                    //cout << getstr(dp[0][k],0,k) << " " << getstr(dp[1][k],1,k) << endl;
                    int len = s.size();
                    if(len > MIN){
                        printf("%d\n",MIN);
                        printf("%s\n",res.c_str());
                        return ;
                    }
                    if(len < MIN){
                        MIN = len;
                        res = s;
                    }else{
                        if(res > s) res = s;
                    }
                }
                que.push(u);
            }
        }
    }
}

int main()
{
    mm[0] = 1;
    for(int i = 1;i <= 30;++i)
        mm[i] = mm[i - 1] * 4;
    int k,cnt = 0;
    scanf("%d",&k);
    while(k--)
    {
        cnt++;
        scanf("%s",s);
        scanf("%s",t);
        int ss,st;
        int a[10],b[10];
        for(int i = 0;i < 9;++i){
            if(s[i] == 'X') a[i] = 0,ss = i;
            else a[i] = s[i] - '0';
            if(t[i] == 'X') b[i] = 0,st = i;
            else b[i] = t[i] - '0';
        }
        int x = cantor(a,9);
        int y = cantor(b,9);
        printf("Case %d: ",cnt);
        bfs((Node){a,x,ss,0,0,0},(Node){b,y,st,1,0,0});
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值