Poj 3414 Pots (BFS+回溯+队列)
这道题需要输出最后结果的执行过程,可以通过结构体,在结构体中定义一个数组s,s中存储了每一步的执行过程,实现了回溯。并且在运行中可以适当剪枝,减少枚举次数。
#include<iostream> #include<queue> #include<cstring> using namespace std; const int N=110; int aa,bb,cc,vis[N][N]; struct node{ int a,b,step,s[N]; }; void BFS(){ memset(vis,0,sizeof(vis)); queue<node> q; node start; start.a=0; start.b=0; start.step=0; vis[start.a][start.b]=1; q.push(start); while(!q.empty()){ start=q.front(); q.pop(); if(start.a==cc || start.b==cc){ cout<<start.step<<endl; for(int i=0;i<start.step;i++){ switch(start.s[i]){ case 1: cout<<"FILL(1)"<<endl;break; case 2: cout<<"FILL(2)"<<endl;break; case 3: cout<<"DROP(1)"<<endl;break; case 4: cout<<"DROP(2)"<<endl;break; case 5: cout<<"POUR(1,2)"<<endl;break; case 6: cout<<"POUR(2,1)"<<endl;break; } } return ; }else{ node next; for(int i=1;i<=6;i++){ next=start; next.s[next.step++]=i; if(i==1 && next.a!=aa) next.a=aa; else if(i==2 && next.b!=bb)next.b=bb; else if(i==3 && next.a) next.a=0; else if(i==4 && next.b) next.b=0; else if(i==5 && next.a && next.b!=bb){ if(next.a+next.b>bb){ next.a=next.a+next.b-bb; next.b=bb; }else{ next.b=next.a+next.b; next.a=0; } }else if(i==6 && next.b && next.a!=aa){ if(next.a+next.b>aa){ next.b=next.a+next.b-aa; next.a=aa; }else{ next.a=next.a+next.b; next.b=0; } } if(vis[next.a][next.b]) continue; vis[next.a][next.b]=1; q.push(next); } } } cout<<"impossible"<<endl; } signed main(){ ios::sync_with_stdio(false); cin.tie(0);cout.tie(0); cin>>aa>>bb>>cc; BFS(); return 0; }
合集:
BFS
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)