HDU - 3567

https://cn.vjudge.net/problem/HDU-3567

 

#include <stdio.h>
#include <math.h>
#include <queue>
#include <stack>
#include <string.h>
using namespace std;

struct Node
{
int s[9];
int loc;//存放0的位置
int state;//存放康托展开后的值
char d;
int fa;
}n[370000];
int len;
int dx[] = {1,0,0,-1};
int dy[] = {0,-1,1,0};
//按照字典序最小来搜索
char dir[] = "dlru";

int vis[9][370000];
long long path[9][370000];

int lev[] = {1,1,2,6,24,120,720,5040,40320,362880};
int cantor(int s[9])
{
int sum = 0;
for(int i = 0;i<9;i++)
{
int num = 0;
//计算逆序数
for(int j = i+1;j<9;j++)
{
if(s[j] < s[i]) num++;
}
sum+=num*lev[9 - i - 1];
}
return sum + 1;
}
void find_path(int pos,int e)
{
long long road = path[pos][e];
stack<int> sta;
int a;
for(int i = 0;i<vis[pos][e] - 1;i++)
{
a = road%4;
road = road>>2;
sta.push(a);
}
while(!sta.empty())
{
a = sta.top();sta.pop();
printf("%c",dir[a]);
}
printf("\n");

}
void bfs(int pos)
{
int head = 0,tail = 0;
n[0].fa = 0;
n[0].d = '\0';
n[0].loc = pos;
n[0].state = cantor(n[0].s);
vis[pos][n[0].state] = 1;
Node cur;
while(head <= tail)
{
cur = n[head];
//if(pos == 6) printf("Cur loc:: %d\n",cur.loc);
int x = cur.loc / 3;
int y = cur.loc % 3;
for(int i = 0 ;i < 4;i++)
{
int nx = x + dx[i];
int ny = y + dy[i];
if(nx>=0&&ny>=0&&nx<3&&ny<3)
{
Node nex = cur;
nex.fa = head;
nex.s[cur.loc] = nex.s[nx*3 + ny];
nex.loc = nx*3 + ny;
nex.s[nex.loc] = 0;
nex.state = cantor(nex.s);

if(!vis[pos][nex.state])
{
vis[pos][nex.state] = vis[pos][cur.state] + 1;
path[pos][nex.state] = (path[pos][cur.state]<<2) + i;
//if(pos == 6) printf("Nex loc:: %d\n",nex.loc);
n[++tail] = nex;
}
}
}
head++;
}
}

 


void init(int pos)
{
for(int i = 0,j = 1;i<9;i++)
{
if(i == pos)//pos代表X的位置
{
n[0].s[i] = 0;//x用0表示
}
else
{
n[0].s[i] = j++;
}
}
//printf("POS :: %d\n",pos);
bfs(pos);
}

int main()
{
int T,t;
int exc[10];
char src[10];
char des[10];
memset(path,0,sizeof path);
memset(vis,0,sizeof vis);
for(int i = 0;i<9;i++)
{
init(i);
}
scanf("%d",&T);
t = T;
while(T--){
scanf("%s",src);
int pos = 0;
for(int i = 0,j = 1;i<9;i++)
{
if(src[i] == 'X'){
src[i] = '0';
pos = i;
exc[0] = 0;
}
else
{
exc[src[i] - '0'] = j++;
}
}
scanf("%s",des);
int s[9];
for(int i = 0;i<9;i++)
{
if(des[i] == 'X')
{
s[i] = 0;
}
else
{
s[i] = exc[des[i] - '0'];
}
}
int tt = cantor(s);
printf("Case %d: %d\n",t-T,vis[pos][tt] - 1);
find_path(pos,tt);
}
return 0;
}

posted on 2019-03-31 18:54  Natsu_iiiiro 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/Natsuiro/p/10632545.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值