题目描述
【题目描述】
有三个容器,容量分别为 a,b,c(a> b > c ),一开始a装满油,现在问是否只靠abc三个容器量出k升油。如果能就输出“yes”,并且说明最少倒几次,否则输出“no”。例如:10升油在10升的容器中,另有两个7升和3升的空容器,要求用这三个容器倒油,使得最后在abc三个容器中有一个刚好存有5升油,问最少的倒油次数是多少?(每次倒油,A容器倒到B容器,或者A内的油倒完,或者B容器倒满。
10 7 3
(10 0 0)
(3 7 0):第一次
(3 4 3):第二次
(6 4 0):第三次
(6 1 3):第四次
(9 1 0):第五次
(9 0 1):第六次
(2 7 1):第七次
(2 5 3):第八次,出现5了。
Input
【输入格式】
有多组测试数据。
输入a,b,c, k四个正整数( 100 ≥ a > b > c≥1 , 1≤k< 100 )
Output
【输出格式】
如果能得到k就输出两行。
第一行“yes”,第二行为最少的次数
否则输出“no”
Sample Input
10 7 3 5
Sample Output
yes
8
将每次变化之后的三个容器中的油的数量转化为bfs过程中搜索到的一步,将容器中油的数量换算成一个数字,然后用map映射标记这个状态是否已经出现过。三个容器相互倒油,一共有六种情况。
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
struct node
{
int a,b,c;//分别表示a,b,c三个容器。
int step;//表示现在是第几步
} start,t1,t2;
int ca,cb,cc;//分别表示三个容器的容量
long int convert(struct node &x)//将三个容器中油的数量状态转化为一个数字
{
long int sum=0;
sum=sum*100+x.a;
sum=sum*100+x.b;
sum=sum*100+x.c;
return sum;
}
bool change(struct node &x,int k)//互相倒油
{
if(k==1&&x.a>0&&x.b<cb)//从a向b倒油
{
if(x.a>=cb-x.b)//从b容器倒满
{
x.a=x.a-(cb-x.b);
x.b=cb;
return true;
}
else//从a内的油倒完
{
x.b=x.b+x.a;
x.a=0;
return true;
}
}
if(k==2&&x.b>0&&x.c<cc)//从b向c倒油
{
if(x.b>=cc-x.c)
{
x.b=x.b-(cc-x.c);
x.c=cc;
return true;
}
else
{
x.c=x.c+x.b;
x.b=0;
return true;
}
}
if(k==3&&x.a>0&&x.c<cc)//从a向c倒油
{
if(x.a>=cc-x.c)
{
x.a=x.a-(cc-x.c);
x.c=cc;
return true;
}
else
{
x.c=x.c+x.a;
x.a=0;
return true;
}
}
if(k==4&&x.b>0&&x.a<ca)//从b向a倒油
{
if(x.b>=ca-x.a)
{
x.b=x.b-(ca-x.a);
x.a=ca;
return true;
}
else
{
x.a=x.a+x.b;
x.b=0;
return true;
}
}
if(k==5&&x.c>0&&x.a<ca)//从c向a倒油
{
if(x.c>=ca-x.a)
{
x.c=x.c-(ca-x.a);
x.a=ca;
return true;
}
else
{
x.a=x.a+x.c;
x.c=0;
return true;
}
}
if(k==6&&x.c>0&&x.b<cb)//从c向b倒油
{
if(x.c>=cb-x.b)
{
x.c=x.c-(cb-x.b);
x.b=cb;
return true;
}
else
{
x.b=x.b+x.c;
x.c=0;
return true;
}
}
return false;
}
int main()
{
int i,k;
while(scanf("%d %d %d %d",&ca,&cb,&cc,&k)!=EOF)
{
if(ca==k)//可能不用倒油
{
printf("yes\n");
printf("0\n");
}
else
{
int flag=0;
int n;
map<long int,bool>p;//map定义在这里
queue<node>q;
start.a=ca;
start.b=0;
start.c=0;
start.step=0;
q.push(start);
p[convert(start)]=true;
while(!q.empty())
{
t1=q.front();
q.pop();
for(i=1; i<=6; i++)
{
t2=t1;
if(change(t2,i))
{
if(p[convert(t2)]==false)
{
p[convert(t2)]=true;
t2.step=t1.step+1;
q.push(t2);
if(t2.a==k||t2.b==k||t2.c==k)
{
flag=1;
n=t2.step;
break;
}
}
}
}
if(flag==1)break;
}
if(flag==1)
{
printf("yes\n");
printf("%d\n",n);
}
else printf("no\n");
}
}
return 0;
}