博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
UVALive 6665 Dragon’s Cruller --BFS,类八数码问题
阅读量:4538 次
发布时间:2019-06-08

本文共 2126 字,大约阅读时间需要 7 分钟。

题意大概就是八数码问题,只不过把空格的移动方式改变了:空格能够向前或向后移动一格或三格(循环的)。

分析:其实跟八数码问题差不多,用康托展开记录状态,bfs即可。

代码:

#include 
#include
#include
#include
#include
#include
#include
#include
#define Mod 1000000007#define SMod 10007#define INint 2147483647#define LL (0x3f3f3f3f3f3f3f3f)*2#define ll long longusing namespace std;#define N 500007struct node{ ll cantor,cost; int pos; bool operator <(const node& a)const { return cost > a.cost; }}S,E;priority_queue
que;ll fact[11] = { 1,1,2,6,24,120,720,5040,40320,362880,3628800};int dx[4] = { 1,-1,3,-3};int a[11],b[11],Can[N][11],vis[N];ll ans,ch,cv;ll Cantor(int *a){ int i,j; ll cnt; ll res = 0; for(i=0;i<9;i++) { cnt = 0; for(j=i+1;j<9;j++) if(a[i] > a[j]) cnt++; res += cnt*fact[8-i]; } return res;}void getcantor(ll cantor,int *a){ for(int i=0;i<9;i++) Can[cantor][i] = a[i];}void geta(ll cantor){ for(int i=0;i<9;i++) a[i] = Can[cantor][i];}void bfs(){ while(!que.empty()) que.pop(); memset(vis,0,sizeof(vis)); int i,j; que.push(S); //vis[S.cantor] = 1; while(!que.empty()) { node tmp = que.top(); que.pop(); ll cantor = tmp.cantor; ll cost = tmp.cost; int pos = tmp.pos; if(vis[cantor]) continue; vis[cantor] = 1; if(cost >= ans) continue; if(cantor == E.cantor) { ans = min(ans,cost); break; } geta(cantor); for(int k=0;k<4;k++) { int v = (pos+dx[k]+9)%9; swap(a[v],a[pos]); ll newcantor = Cantor(a); if(vis[newcantor]) { swap(a[v],a[pos]); continue; } getcantor(newcantor,a); swap(a[v],a[pos]); node now; now.cantor = newcantor; now.pos = v; if(k < 2) now.cost = cost + ch; else now.cost = cost + cv; if(now.cost >= ans) continue; //vis[newcantor] = 1; que.push(now); } }}int main(){ int i,j; while(scanf("%lld%lld",&ch,&cv) && (ch||cv)) { for(i=0;i<9;i++) { scanf("%d",&a[i]); if(a[i] == 0) S.pos = i; } S.cantor = Cantor(a); S.cost = 0; for(i=0;i<9;i++) scanf("%d",&b[i]); E.cantor = Cantor(b); getcantor(S.cantor,a); getcantor(E.cantor,b); ans = (1LL<<62); bfs(); printf("%lld\n",ans); } return 0;}
View Code

 

转载于:https://www.cnblogs.com/whatbeg/p/3908069.html

你可能感兴趣的文章
Python基础---OS模块 (二)
查看>>
【JS点滴】substring和substr以及slice和splice的用法和区别。
查看>>
awk多模式匹配
查看>>
线段树
查看>>
a span等行内元素加margin属性后无效果解决方案
查看>>
傻瓜式硬盘重装win7系统图文加视频教程
查看>>
BZOJ 1607 [Usaco2008 Dec]Patting Heads 轻拍牛头:统计 + 筛法【调和级数】
查看>>
如果一个人请优雅的活着。
查看>>
验证码
查看>>
Django缓存配置
查看>>
Ubuntu下安装 Mysql
查看>>
LeetCode--Reverse Integer
查看>>
PHP_APC+Ajax实现的监视进度条的文件上传
查看>>
计算机网络课堂笔记3.29
查看>>
word2vec----CBOW
查看>>
衰减学习率真的有用吗?
查看>>
ORACLE 建库过程总结
查看>>
Ogre1.8.1 Basic Tutorial 6 - The Ogre Startup Sequence
查看>>
构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(36)-文章发布系统③-kindeditor使用...
查看>>
c# Winform 开发分屏显示应用程序
查看>>