B29 IDA*算法 Booksort
视频链接:130 IDA算法 Booksort_哔哩哔哩_bilibili
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int N=16; int n,dep; int a[N],b[5][N]; //b是a的每层备份 int f(){ //估价函数: 修正错误连接的次数⌈tot/3⌉ int tot=0; for(int i=0; i<n-1; i++) if(a[i+1]!=a[i]+1) tot++; //错误连接数 return (tot+2)/3; //每次最多修正3个错误连接 } bool check(){ //检查正确顺序 for(int i=0; i<n; i++) if(a[i]!=i+1) return false; return true; } bool dfs(int u){ if(u+f()>dep) return false; //越界 if(check()) return true; //成功 for(int i=0; i<n; i++) for(int j=i+1; j<n; j++) for(int k=j,x,y; k<n; k++){ memcpy(b[u],a,sizeof a); //备份 for(x=j,y=i; x<=k; x++,y++) a[y]=b[u][x]; //[j,k]前插至i for(x=i; x<=j-1; x++,y++) a[y]=b[u][x]; //[i,j-1]后移 if(dfs(u+1)) return true; memcpy(a,b[u],sizeof a); //恢复现场 } return false; } int main(){ int T; cin>>T; while(T--){ cin>>n; for(int i=0; i<n; i++) cin>>a[i]; for(dep=0; dep<5&&!dfs(0); dep++); if(dep>=5) puts("5 or more"); else printf("%d\n",dep); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
2022-06-25 D23 网络流 费用流 EK 算法
2022-06-25 D22 网络流 最小割 Dinic 算法