POJ 1606 Jugs(BFS:找最短路径并输出)
2014-05-11 21:07
423 查看
POJ 1606 Jugs(BFS:找最短路径并输出)
http://poj.org/problem?id=1606
题意:
又是给你两个容量为A和B的水杯,要你倒出B杯子有C升水的路径.
分析:
本题之前我就做过一道类似的的:
/article/1517581.html
上面有分析.下面直接给出代码:
AC代码:
http://poj.org/problem?id=1606
题意:
又是给你两个容量为A和B的水杯,要你倒出B杯子有C升水的路径.
分析:
本题之前我就做过一道类似的的:
/article/1517581.html
上面有分析.下面直接给出代码:
AC代码:
#include<cstdio> #include<cstring> #include<algorithm> #include<queue> #include<stack> using namespace std; const int maxr=100+5; const int maxc=100+5; const int maxn=10000+100;//这个规模是测试OJ得出的 int A,B,C; int vis[maxr][maxc],dist[maxr][maxc],pre[maxr][maxc]; struct Cell { int a,b; Cell(int a,int b):a(a),b(b){} }; int cnt; struct Node { int a,b; int t; Node(){} Node(int a,int b,int t):a(a),b(b),t(t){} }nodes[maxn]; Cell BFS() { queue<Cell> Q; Q.push(Cell(0,0)); memset(vis,0,sizeof(vis)); vis[0][0]=1; dist[0][0]=0; cnt=0; while(!Q.empty()) { Cell cell=Q.front();Q.pop(); int a=cell.a,b=cell.b; for(int d=0;d<6;d++) { int na,nb; if(d==0){na=A,nb=b;} else if(d==1) {na=a,nb=B;} else if(d==2) {na=0,nb=b;} else if(d==3) {na=a,nb=0;} else if(d==4) { int all=a+b; na= all>=B?all-B:0; nb= all>=B? B:all; } else if(d==5) { int all=a+b; na= all>=A? A:all; nb= all>=A? all-A:0; } if(vis[na][nb]==0) { vis[na][nb]=1; dist[na][nb]=dist[a][b]+1; nodes[cnt++]=Node(a,b,d); pre[na][nb]=cnt-1; Q.push(Cell(na,nb)); if(nb==C) return Cell(na,nb); } } } return Cell(-1,-1); } int main() { while(scanf("%d%d%d",&A,&B,&C)==3) { Cell cell=BFS(); stack<int> S; int a=cell.a ,b=cell.b; while(true) { int tmp=pre[a][b]; S.push(nodes[tmp].t); a=nodes[tmp].a,b=nodes[tmp].b; if(a==0&&b==0) break; } while(!S.empty()) { int t=S.top();S.pop(); if(t==0) printf("fill A\n"); else if(t==1) printf("fill B\n"); else if(t==2) printf("empty A\n"); else if(t==3) printf("empty B\n"); else if(t==4) printf("pour A B\n"); else if(t==5) printf("pour B A\n"); } printf("success\n"); } return 0; }
相关文章推荐
- POJ 3984---迷宫问题(BFS,迷宫最短路径且输出路径)
- POJ 3984 迷宫问题(BFS:迷宫最短路径且输出路径)
- poj 1606 Jugs(广搜BFS+路径输出)
- [POJ] 1606 Jugs(BFS+路径输出)
- POJ 3322 Bloxorz I(BFS:求迷宫最短路径)
- poj迷宫问题(bfs路径输出)
- K - 迷宫问题 POJ 3984 BFS路径输出
- POJ 1545 / ZOJ 1333 Galactic Import (bfs || 最短路径)
- 设计一个算法,採用BFS方式输出图G中从顶点u到v的最短路径(不带权的无向连通图G採用邻接表存储)
- 设计一个算法,采用BFS方式输出图G中从顶点u到v的最短路径(不带权的无向连通图G采用邻接表存储)
- 算法训练之BFS POJ 2251 Dungeon Master 三维最短路径
- poj 3414 Pots【bfs+回溯路径 正向输出】
- poj 3984 迷宫问题(BFS+输出路径)
- POJ 3414 Pots (BFS记录最短路径)
- POJ - 3414 Pots解题报告(输出路径的bfs)
- OJ 3984 迷宫问题(BFS:迷宫最短路径且输出路径)
- poj 1606 Jugs (bfs)
- POJ 3278 爬格子 (bfs求最短路径)
- poj 1606 Jugs and poj 3414 Pots(数组模拟BFS) uva 571 (数论)
- poj-3084 输出路径的BFS