首页 > 代码库 > pots(BFS)
pots(BFS)
D - Pots
Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%lld & %lluDescription
You are given two pots, having the volume of A and B liters respectively. The following operations can be performed:
Input
On the first and only line are the numbers A, B, and C. These are all integers in the range from 1 to 100 and C≤max(A,B).
Output
The first line of the output must contain the length of the sequence of operations K. If the desired result can’t be achieved, the first and only line of the file must contain the word ‘impossible’.
Sample Input
3 5 4
Sample Output
6
Hint
题意:两个水杯,已知体积A,B,经过三种转换方式达到C状态
1.清空水杯A/B
2.装满A/B
3.把A/B杯中的水倒入B/A中
简单BFS 题目的原型是POJ3414 简化
#include <iostream> #include <cstdio> #include <cstring> #include <queue> using namespace std; int A, B, C; int vis[105][105]; struct node { int a, b, step; }; void BFS() { queue <node> q; int sa,sb; node f,t; f.a = 0; f.b = 0; f.step = 0; vis[f.a][f.b] = 1; q.push(f); while (!q.empty()) { t = q.front(); q.pop(); if (t.a == C || t.b == C) { printf("%d\n",t.step); return ; } for (int i = 1; i <= 6; i++) { if (i == 1) //装满A { sa = A;sb = t.b; } else if (i == 2)//装满B { sa = t.a; sb = B; } else if (i == 3)//把B中水倒入A { if (t.a + t.b > A) {sb = t.a + t.b - A;sa = A;} else {sb = 0; sa = t.a + t.b;} } else if (i == 4)//把A中水倒入B { if (t.a + t.b > B) {sa = t.a + t.b - B; sb = B;} else { sa = 0; sb = t.a + t.b; } } else if (i == 5)//清空A {sa = 0; sb = t.b;} else {sa = t.a; sb = 0;}//清空B if (!vis[sa][sb]) { vis[sa][sb] = 1; f.a = sa; f.b = sb; f.step = t.step + 1; q.push(f); } } } puts("impossible"); } int main() { while (scanf("%d%d%d", &A, &B, &C) != EOF) { memset(vis, 0, sizeof(vis)); BFS(); } return 0; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。