(简单) POJ 3414 Pots,BFS+记录路径。

时间:2021-11-02 20:25:39

  Description

  You are given two pots, having the volume of A and B liters respectively. The following operations can be performed:

  1. FILL(i)        fill the pot i (1 ≤ i ≤ 2) from the tap;
  2. DROP(i)      empty the pot i to the drain;
  3. POUR(i,j)    pour from pot i to pot j; after this operation either the pot j is full (and there may be some water left in the pot i), or the pot i is empty (and all its contents have been moved to the pot j).

  Write a program to find the shortest possible sequence of these operations that will yield exactly C liters of water in one of the pots.

  就是对两个杯子进行操作了,装满,倒空,倒过去。两个水杯里的水表示一个状态,然后BFS就好,要记录路径的话,记住每一个的父亲,然后最后反着来一遍就好了。

代码如下:

#include<iostream>
#include<cstring>
#include<cmath>
#include<queue> using namespace std; int A,B,C;
int rem[][];
int shorem[]; struct state
{
int a,b;
int type;
int faa,fab;
int num; state() {}
}; state sta[][]; void showans(state *e)
{
int cou=; while(e->a||e->b)
{
shorem[cou++]=e->type; e=&sta[e->faa][e->fab];
} cout<<cou<<endl;
for(int i=cou-;i>=;--i)
switch(shorem[i])
{
case :
cout<<"FILL(1)\n";
break;
case :
cout<<"FILL(2)\n";
break;
case :
cout<<"DROP(1)\n";
break;
case :
cout<<"DROP(2)\n";
break;
case :
cout<<"POUR(1,2)\n";
break;
case :
cout<<"POUR(2,1)\n";
break;
} } void slove()
{
queue <state *> que;
state *temp;
int t1,t2,t3; sta[][].faa=sta[][].fab=-;
sta[][].type=;
sta[][].num=;
que.push(&sta[][]); while(!que.empty())
{
temp=que.front();
que.pop(); if(temp->a==C||temp->b==C)
{
showans(temp);
return;
} t1=temp->a;
t2=temp->b; if(sta[A][t2].num==-)
{
sta[A][t2].num=temp->num+;
sta[A][t2].faa=t1;
sta[A][t2].fab=t2;
sta[A][t2].type=; que.push(&sta[A][t2]);
}
if(sta[t1][B].num==-)
{
sta[t1][B].num=temp->num+;
sta[t1][B].faa=t1;
sta[t1][B].fab=t2;
sta[t1][B].type=; que.push(&sta[t1][B]);
}
if(sta[][t2].num==-)
{
sta[][t2].num=temp->num+;
sta[][t2].faa=t1;
sta[][t2].fab=t2;
sta[][t2].type=; que.push(&sta[][t2]);
}
if(sta[t1][].num==-)
{
sta[t1][].num=temp->num+;
sta[t1][].faa=t1;
sta[t1][].fab=t2;
sta[t1][].type=; que.push(&sta[t1][]);
}
t3=min(t1,B-t2);
if(sta[t1-t3][t2+t3].num==-)
{
sta[t1-t3][t2+t3].num=temp->num+;
sta[t1-t3][t2+t3].faa=t1;
sta[t1-t3][t2+t3].fab=t2;
sta[t1-t3][t2+t3].type=; que.push(&sta[t1-t3][t2+t3]);
}
t3=min(t2,A-t1);
if(sta[t1+t3][t2-t3].num==-)
{
sta[t1+t3][t2-t3].num=temp->num+;
sta[t1+t3][t2-t3].faa=t1;
sta[t1+t3][t2-t3].fab=t2;
sta[t1+t3][t2-t3].type=; que.push(&sta[t1+t3][t2-t3]);
}
} cout<<"impossible\n";
} int main()
{
ios::sync_with_stdio(false); for(int i=;i<=;++i)
for(int j=;j<=;++j)
{
sta[i][j].a=i;
sta[i][j].b=j;
} while(cin>>A>>B>>C)
{
for(int i=;i<=;++i)
for(int j=;j<=;++j)
sta[i][j].num=-; slove();
} return ;
}