Pots
题目描述
You are given two pots, having the volume of A and B liters respectively. The following operations can be performed:
FILL(i) fill the pot i (1 ≤ i ≤ 2) from the tap;
DROP(i) empty the pot i to the drain;
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.
输入
On the first and only line are the numbers A, B, and C. These are all integers in the range from 1 to 100 and C≤max(A,B).
输出
The first line of the output must contain the length of the sequence of operations K. If the desired result can’t be achieved, the first and only line of the file must contain the word ‘impossible’.
示例输入
3 5 4
示例输出
6
提示
FILL(2)
POUR(2,1)
DROP(1)
POUR(2,1)
FILL(2)
POUR(2,1)
这道题是一道BFS的运用,有六种状态:
1.将A中的水倒满;
2.将B中的水倒满;
3.将A中的水倒空;
4.将B种的水倒空;
5.将A中的水倒入B中;
6.将B中的水倒入A中(考虑杯中是否已满);
<span style="font-size:18px;color:#009900;">#include <iostream>
#include<stdio.h>
#include<math.h>
#include<string.h>
using namespace std;
int vis[101][101];
struct node
{
int x;
int y;
int num;
}p[10001],t,f;
int bfs(int a,int b,int c)
{
int e=0,r=0,i;
t.x=0;
t.y=0;
t.num=0;
p[e++]=t;
vis[t.x][t.y]=1;
while(e>r)
{
t=p[r++];
if(t.x==c||t.y==c)
{
printf("%d\n",t.num);
return 0;
}
for(i=0;i<6;i++)
{
if(i==0)
{
f.x=t.x;
f.y=b;
}
if(i==1)
{
f.x=a;
f.y=t.y;
}
if(i==2)
{
f.x=0;
f.y=t.y;
}
if(i==3)
{
f.x=t.x;
f.y=0;
}
if(i==4)
{
f.x=t.x+t.y;
if(f.x>a)
{
f.y=f.x-a;
f.x=a;
}
else
f.y=0;
}
if(i==5)
{
f.y=t.x+t.y;
if(f.y>b)
{
f.x=f.y-b;
f.y=b;
}
else
f.x=0;
}
if(vis[f.x][f.y]==0)
{
f.num=t.num+1;
p[e++]=f;
vis[f.x][f.y]=1;
}
}
}
printf("impossible\n");
return 0;
}
int main()
{
int a,b,c;
while(scanf("%d%d%d",&a,&b,&c)!=EOF)
{
memset(vis,0,sizeof(vis));
bfs(a,b,c);
}
return 0;
}
</span>