Description
给你两个容器,求出获得指定量水的步骤
三个操作
FILL(A):将A容器装满水
DROP(A):将A容器中的水倒出
POUR(A,B):将A容器中的水全部倒入B容器中
Input
每组用例包括三个整数A,B,C,以文件尾结束输入
Output
对于每组用例,输出获得C体积水的步骤,如果不存在可行解则输出impossible
Sample Input
3 5 4
Sample Output
6
FILL(2)
POUR(2,1)
DROP(1)
POUR(2,1)
FILL(2)
POUR(2,1)
Solution
简单模拟+dfs
每次最多有六种情况,填满a,填满b,清空a,清空b,从a倒到b,从b倒到a。对每种情况将在这种情况下的可能的情况进入队列,直到找到最终结果
注意:倒的方法可能有多种,由于是special judge,所以输出任意一种可行解即可
Code
#include <iostream>
#include <queue>
#include <map>
#include <string>
#include <cmath>
using namespace std;
struct Data
{
int x,y;
string s;
bool operator <(Data b) const
{
if(x!=b.x) return x<b.x;
return y<b.y;
}
};
int main()
{
int A,B,C,sum;
Data t,temp;
cin>>A>>B>>C;
t.x=t.y=0;//初始状态两桶中均没水
temp.x=-1;
queue<Data> Q;
map<Data,Data> M;//储存操作队列
while(!Q.empty())//清空队列
Q.pop();
Q.push(t);
M[t]=temp;
while(!Q.empty())
{
t=Q.front();
Q.pop();
if(t.x==C||t.y==C)//遇到可行解
break;
temp.x=A;
temp.y=t.y;
temp.s="FILL(1)";//填满A
if(M.find(temp)==M.end())
Q.push(temp),M[temp]=t;
temp.x=t.x;
temp.y=B;
temp.s="FILL(2)";//填满B
if(M.find(temp)==M.end())
Q.push(temp),M[temp]=t;
temp.x=0;
temp.y=t.y;
temp.s="DROP(1)";//清空A
if(M.find(temp)==M.end())
Q.push(temp),M[temp]=t;
temp.x=t.x;
temp.y=0;
temp.s="DROP(2)";//清空B
if(M.find(temp)==M.end())
Q.push(temp),M[temp]=t;
temp.x=min(t.x+t.y,A);
temp.y=max(0,t.y-A+t.x);
temp.s="POUR(2,1)";//B倒A
if(M.find(temp)==M.end())
Q.push(temp),M[temp]=t;
temp.x=max(0,t.x-B+t.y);
temp.y=min(t.x+t.y,B);
temp.s="POUR(1,2)";//A倒B
if(M.find(temp)==M.end())
Q.push(temp),M[temp]=t;
}
if(t.x==C||t.y==C)
{
string ans="";
sum=0;
for(temp=t;temp.x||temp.y;temp=M[temp])
ans=temp.s+"\n"+ans,sum++;
cout<<sum<<endl<<ans;//按格式输出
}
else
cout<<"impossible"<<endl;//按格式输出
return 0;
}