当前位置: 首页 > news >正文

【代码】八数码难题模板 [宽搜]

P1379 八数码难题 - 洛谷

/*
1 2 3
4 5 6
7 8 9
*/
#include<bits/stdc++.h>
using namespace std;typedef long long LL;
const LL inf = 1e9;
LL st, ed;
map<LL, bool> mp;struct State {LL s;    // 状态 int p;   // 0 的位置 int k;  // 当前移动次数 
};LL swap_state(LL sta, int x, int y) {  // 交换状态 sta 里第 x 个和第 y 个的位置 if (x > y) {swap(x, y);}int t = 0, a, b;for (LL i = inf; i >= 10; i /= 10) {t ++;if (t == x) {a = (sta % i) / (i / 10);}if (t == y) {b = (sta % i) / (i / 10);}} LL new_s = sta;t = 0;for (LL i = inf; i >= 10; i /= 10) {t ++;if (t == x) {new_s -= a * (i / 10);new_s += b * (i / 10);}if (t == y) {new_s -= b * (i / 10);new_s += a * (i / 10);}} return new_s;
}int get_ans(State tmp) {queue<State> Q;Q.push(tmp);while (!Q.empty()) {State x = Q.front(); Q.pop();if (mp[x.s]) {continue;}mp[x.s] = 1;if (x.s == ed) {return x.k;}if (x.p - 3 > 0) {  // 0 的位置不在最上面一行,可以和上面的数交换位置 State tmp = {swap_state(x.s, x.p, x.p - 3), x.p - 3, x.k + 1};Q.push(tmp);}if (x.p + 3 <= 9) {  // 0 的位置不在最下面一行,可以和下面的数交换位置 State tmp = {swap_state(x.s, x.p, x.p + 3), x.p + 3, x.k + 1};Q.push(tmp);}if (x.p % 3 != 1) {  // 0 的位置不在最左边一列,可以和左边的数交换位置 State tmp = {swap_state(x.s, x.p, x.p - 1), x.p - 1, x.k + 1};Q.push(tmp);}if (x.p % 3 != 0) {  // 0 的位置不在最右边一列,可以和右边的数交换位置 State tmp = {swap_state(x.s, x.p, x.p + 1), x.p + 1, x.k + 1};Q.push(tmp);}}return 0;
}int main () {ios::sync_with_stdio(false);cin.tie(0);cin >> st;State tmp = {st, 0, 0};// 找初始状态 0 的位置 for (LL i = inf; i >= 10; i /= 10) {tmp.p ++; if ((st % i) / (i / 10) == 0) {break;}}ed = 123804765;cout << get_ans(tmp) << "\n";return 0;
}

http://www.dtcms.com/a/532988.html

相关文章:

  • 震惊!这家滑雪租赁服务商竟让千万用户疯狂抢订!
  • JSP技术入门指南十IDEA开发环境下MySQL数据可视化展示与前后端交互实战
  • 网站建设的思想静态html怎么部署到服务器
  • 餐饮网站建设的目的如何制作境外网站
  • [nanoGPT] configurator.py | exec() globals()
  • 【瑞芯微】【rk3128】【01.使用docker搭建rk3128 编译烧录环境】
  • 企业官网网站优化公司现在网站给源码
  • 知春路网站建设网站建设网络推广柯
  • 002-Spring AI Alibaba Prompt 功能完整案例
  • 网站栏目设计优化方案驾校网站源码下载
  • 大模型-模型压缩:量化、剪枝、蒸馏、二值化 (2)
  • 做文章网站汕尾建设网站首页
  • 数据结构<C++>——链表
  • 数据结构-并查集
  • 该如何建设和优化一个网站网页设计与制作工资多少
  • 建设自己的网站有什么wordpress radiate
  • Peppa Pig - Gardening
  • 蒙文门户网站建设淘宝seo搜索优化工具
  • html基本标签
  • 肇庆网站制作软件枫林seo
  • 网站地址申请极简网站模板
  • 《首屏加载优化手册:Vue3+Element Plus项目提速的技术细节》
  • typora1.9.5安装与激活
  • 自适应网站模板企业网站建设一般步骤
  • 我在高职教STM32(新07)——按键输入实验
  • Rust 与 WebAssembly:构建高效前端应用的全流程复盘
  • 网站百度搜索情况和反链接优化建议哪里有营销型网站最新报价
  • 设计模式-备忘录模式(Memento)
  • 河南建设厅特种工报考网站网站管理与建设总结
  • 烟台网站建设推广网站建设交印花税嘛