题目来源: poj 3414
问题描述
有两个空壶,最终要将其中一个壶装水量达到给定值。对壶有3种操作方式,一是开水龙头装满,二是倒光,三是将其中一个壶的水倒到另一个壶里,且水倒光或者另一个壶装满。若能实现目标则输出最小步骤数且按顺序输出操作,若不能实现,则输出“impossible”
未AC…之后再看
#include <iostream>
#include <queue>
#include <string>
#include <vector>
using namespace std;
struct node
{
int num[2];
int step;
vector<string> v;
} start;
int volume[2];
int k; //要量的值
bool has = false;
void BFS()
{
bool vis[201][201] = {false};
queue<node> Q;
start.num[0] = start.num[1] = 0;
start.step = 0;
vis[0][0] = true;
Q.push(start);
while (!Q.empty())
{
node top = Q.front();
Q.pop();
if (top.num[0] == k || top.num[1] == k)
{
cout << top.step << endl;
for (int i = 0; i < top.step; i++)
{
cout << top.v[i] << endl;
has = true;
}
return;
}
if (top.num[0] < volume[0]) //fill A
{
node temp = top;
temp.num[0] = volume[0];
temp.step = top.step + 1;
string ss = "FILL (1)";
if (vis[temp.num[0]][temp.num[1]] == false)
{
vis[temp.num[0]][temp.num[1]] = true;
temp.v.push_back(ss);
Q.push(temp);
}
}
if (top.num[1] < volume[1]) //fill B
{
node temp = top;
temp.num[1] = volume[1];
temp.step = top.step + 1;
string ss = "FILL (2)";
if (vis[temp.num[0]][temp.num[1]] == false)
{
vis[temp.num[0]][temp.num[1]] = true;
temp.v.push_back(ss);
Q.push(temp);
}
}
if (top.num[0] > 0) //DROP A
{
node temp = top;
temp.num[0] = 0;
temp.step = top.step + 1;
string ss = "DROP (1)";
if (vis[temp.num[0]][temp.num[1]] == false)
{
vis[temp.num[0]][temp.num[1]] = true;
temp.v.push_back(ss);
Q.push(temp);
}
}
if (top.num[1] > 0) //DROP B
{
node temp = top;
temp.num[1] = 0;
temp.step = top.step + 1;
string ss = "DROP (2)";
if (vis[temp.num[0]][temp.num[1]] == false)
{
vis[temp.num[0]][temp.num[1]] = true;
temp.v.push_back(ss);
Q.push(temp);
}
}
if (top.num[0] >= top.num[1]) //POUR (1,2)
{
node temp = top;
int rest = volume[1] - temp.num[1]; //2中还可以装多少水
if (temp.num[0] > rest) //2可以装满
{
temp.num[0] -= rest;
temp.num[1] = volume[1];
}
else
{
temp.num[0] = 0;
temp.num[1] += temp.num[0];
}
temp.step = top.step + 1;
string ss = "POUR (1,2)";
temp.v.push_back(ss);
if (vis[temp.num[0]][temp.num[1]] == false)
{
vis[temp.num[0]][temp.num[1]] = true;
Q.push(temp);
}
}
if (top.num[0] <= top.num[1]) //POUR (2,1)
{
node temp = top;
int rest = volume[0] - temp.num[0]; //2中还可以装多少水
if (temp.num[1] > rest) //2可以装满
{
temp.num[1] -= rest;
temp.num[0] = volume[0];
}
else
{
temp.num[1] = 0;
temp.num[0] += temp.num[1];
}
temp.step = top.step + 1;
string ss = "POUR (2,1)";
temp.v.push_back(ss);
if (vis[temp.num[0]][temp.num[1]] == false)
{
vis[temp.num[0]][temp.num[1]] = true;
Q.push(temp);
}
}
}
}
int main()
{
while (cin >> volume[0] >> volume[1] >> k)
{
BFS();
if (!has)
{
cout << "impossible" << endl;
}
has = false;
}
return 0;
}