poj3414 Pots(BFS)

题目链接

http://poj.org/problem?id=3414

题意

有两个杯子,容量分别为A升,B升,可以向杯子里倒满水,将杯子里的水倒空,将一个杯子里的水倒到另一个杯子里,求怎样倒才能使其中的一个杯子里的水恰为C升,输出最少步数和操作;如果不能倒到C升,输出“impossible”。

思路

这题与poj1606基本相同,在poj1606的基础上添加了输出最少步数,修改了操作的表示,以及不可能达到目标时输出impossible。将poj1606的代码略作修改即可。

代码

 #include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <stack>
using namespace std; struct Node
{
int a, b;
int steps;
int flag;
Node* pre;
}; const int N = ;
int ca, cb, n;
int visit[N][N];
stack<int> s; void print()
{
while (!s.empty())
{
switch (s.top())
{
case :
cout << "FILL(1)" << endl;
break;
case :
cout << "FILL(2)" << endl;
break;
case :
cout << "DROP(1)" << endl;
break;
case :
cout << "DROP(2)" << endl;
break;
case :
cout << "POUR(1,2)" << endl;
break;
case :
cout << "POUR(2,1)" << endl;
break;
}
s.pop();
}
} void bfs(int a, int b)
{
Node state[N];
int cnt = -;
memset(visit, , sizeof(visit));
Node node;
node.a = node.b = ;
node.steps = ;
node.pre = NULL;
queue<Node> q;
q.push(node);
visit[node.a][node.b] = ;
while (!q.empty())
{
Node node = q.front();
q.pop();
state[++cnt] = node;
Node next = node;
for (int i = ; i < ; i++)
{
next = node;
int amount;
switch (i)
{
case : //FILL(1)
next.a = ca;
next.flag = ;
break;
case : //FILL(2)
next.b = cb;
next.flag = ;
break;
case : // DROP(1)
next.a = ;
next.flag = ;
break;
case : //DROP(2)
next.b = ;
next.flag = ;
break;
case : //POUR(1,2)
amount = cb - node.b;
if (node.a > amount)
{
next.a -= amount;
next.b = cb;
}
else {
next.a = ;
next.b = node.a + node.b;
}
next.flag = ;
break;
case : //POUR(2,1)
amount = ca - node.a;
if (node.b > amount)
{
next.a = ca;
next.b -= amount;
}
else {
next.a = node.a + node.b;
next.b = ;
}
next.flag = ;
break;
} if (!visit[next.a][next.b])
{
visit[next.a][next.b] = ;
next.pre = &state[cnt];
next.steps = node.steps + ;
if (next.a == n || next.b == n)
{
cout << next.steps << endl;
while (next.pre)
{
s.push(next.flag);
next = *next.pre;
}
print();
return;
}
q.push(next);
}
}
}
cout << "impossible" << endl;
} int main()
{
cin >> ca >> cb >> n;
bfs(, );
return ;
}

 相似题目

1、poj1606 Jugs

上一篇:myeclipse保存时弹出Building workspace


下一篇:SCons - 简单而强大的项目编译脚本