问题 E: 【宽搜入门】巧妙取量
时间限制: 2 Sec 内存限制: 128 MB
提交: 27 解决: 10
题目描述
【题目描述】
有三个容器,容量分别为 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,但是要注意一点,BFS中,根据实际问题,很多的问题都需要一个标记数组或者映射来反映某种情况是否出现过,要根据具体问题选择合适的数据结构进行表示。还有就是各种剪枝条件,可以大大加快程序的运行速度,多注意一下就行啦~~
正确代码
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
bool f[105][105][105];
struct node
{
int jugs[3];
int step;
node(int s,int a,int b,int c)
{
step=s;
jugs[0]=a;
jugs[1]=b;
jugs[2]=c;
}
};
int combine(int a,int b,int c,int k)
{
queue<node> p;
node s(0,a,0,0);
f[a][0][0]=true;
p.push(s);
int capacity[3];
capacity[0]=a;
capacity[1]=b;
capacity[2]=c;
int temp[3];
int remain;
while(!p.empty())
{
s=p.front();
p.pop();
if(s.jugs[0]==k||s.jugs[1]==k||s.jugs[2]==k)
{
printf("yes\n%d\n",s.step);
while(!p.empty())
p.pop();
return 1;
}
for(int i=0;i<3;i++)
{
if(s.jugs[i]!=0)
{
for(int j=0;j<3;++j)
{
remain=capacity[j]-s.jugs[j];
if(j!=i&&remain!=0)
{
for(int x=0;x<3;++x)
temp[x]=s.jugs[x];
if(s.jugs[i]<remain)
{
temp[j]+=temp[i];
temp[i]=0;
}
else
{
temp[i]-=remain;
temp[j]=capacity[j];
}
if(f[temp[0]][temp[1]][temp[2]]==false)
{
f[temp[0]][temp[1]][temp[2]]=true;
node r(s.step+1,temp[0],temp[1],temp[2]);
p.push(r);
}
}
}
}
}
}
return 0;
}
int main()
{
int a,b,c,k,temp;
while(~scanf("%d %d %d %d",&a,&b,&c,&k))
{
if(a>b&&b>c&&c>=1&&a<=100&&k>=1&&k<=100&&k<=a)
{
memset(f,0,sizeof(f));
int flag=combine(a,b,c,k);
if(flag==0)
printf("no\n");
}
else
{
printf("no\n");
}
}
return 0;
}