c九宫重排_九宫重排

#include

#include

#include

#include

#include

using namespace std;

const int N = 400000;

#define state pair

#define hash first

#define pos second

int factor[10];

int step[N];

int st[N];

int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};

int cantor(const string &s){

int res = 0;

for(int i = 0; i < s.size(); i ++){

int cnt = 0;

for(int j = i + 1; j < s.size(); j ++){

if(s[j] < s[i]) cnt ++;

}

res += cnt * factor[8 - i];

}

return res;

}

string decantor(int hash){

string t = ".12345678";

int len = 9;

string s;

for(int i = 8; i >= 0; i --){

int l = hash / factor[i];

hash %= factor[i];

s += t[l];

for(int j = l + 1; j < len; j ++) t[j - 1] = t[j];

len --;

}

return s;

}

int bfs(const state &s, int aim){

queue q;

q.push(s);

st[s.hash] = 1;

while(q.size()){

state h = q.front();

q.pop();

int x = h.pos / 3, y = h.pos % 3;

string t = decantor(h.hash);

for(int i = 0; i < 4; i ++){

int a = x + dx[i], b = y + dy[i];

if(a < 0 || b < 0 || a >= 3 || b >= 3) continue;

int pos = a * 3 + b;

swap(t[pos], t[h.pos]);

int ct = cantor(t);

swap(t[pos], t[h.pos]);

if(st[ct]) continue;

q.push({ct, pos});

st[ct] = 1;

step[ct] = step[h.hash] + 1;

if(aim == ct) return step[ct];

}

}

return -1;

}

void init(){

factor[0] = 1;

for(int i = 1; i < 10; i ++)

factor[i] = factor[i - 1] * i;

}

int main(){

init();

string start, aim;

cin >> start >> aim;

int pos = 0;

for(int i = 0; i < start.size(); i ++)

if(start[i] == '.'){

pos = i;

break;

}

cout << bfs({cantor(start), pos}, cantor(aim));

return 0;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值