题目大意:
有两个容量分别为a,b的杯子,需要经过若干次变换使任意一个杯子的容量为c,求最短的变换路径
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
int a,b,k;
int vis[105][105];
struct node
{
int x,y,step;
string path;
};
string p[] = {"FILL(2)","FILL(1)","POUR(2,1)","POUR(1,2)","DROP(1)","DROP(2)"};
void print(node cur)
{
cout << cur.step << endl;
for (int i = 0; i < cur.path.size(); ++i)
cout << p[cur.path[i]-'0'] << endl;
}
int BFS()
{
node cur,next;
cur.x = 0;
cur.y = 0;
cur.step = 0;
cur.path = "";
queue <node> q;
q.push(cur);
while(!q.empty())
{
cur = q.front();
q.pop();
if (cur.x == k|| cur.y == k)
{
print(cur);
return 0;
}
/*fill*/
if (cur.x != a)
{
next = {a,cur.y,cur.step+1};
if (!vis[a][cur.y])
{
next.path = cur.path + "1";
q.push(next);
vis[a][cur.y] = 1;
}
}
if (cur.y != b)
{
next = {cur.x,b,cur.step+1};
if (!vis[cur.x][b])
{
next.path = cur.path + "0";
q.push(next);
vis[cur.x][b] = 1;
}
}
/*drop*/
next = {0,cur.y,cur.step+1};
if(!vis[0][cur.y])
{
next.path = cur.path + "4";
q.push(next);
vis[0][cur.y] = 1;
}
next = {cur.x,0,cur.step+1};
if (!vis[cur.x][0])
{
next.path = cur.path + "5";
q.push(next);
vis[cur.x][0] = 1;
}
/*pour*/
if (cur.x != a && cur.y != 0)
{
int t1 = cur.x, t2 = cur.y;
if (a - t1 <= t2)
next = {a,t2-a+t1,cur.step+1};
else
next = {t1+t2,0,cur.step+1};
if (!vis[next.x][next.y])
{
next.path = cur.path + "2";
vis[next.x][next.y] = 1;
q.push(next);
}
}
if (cur.y != b && cur.x != 0)
{
int t1 = cur.x, t2 = cur.y;
if (b - t2 <= t1)
next = {t1-b+t2,b,cur.step+1};
else
next = {0,t1+t2,cur.step+1};
if (!vis[next.x][next.y])
{
next.path = cur.path + "3";
vis[next.x][next.y] = 1;
q.push(next);
}
}
}
return -1;
}
int main()
{
while(cin >> a >> b >> k)
{
memset(vis,0,sizeof(vis));
if (BFS() == -1)
cout << "impossible" << endl;
}
return 0;
}