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)
这题本是POJ3414,都是BFS,但是本题比那个简单多了。没有记录状态的这个。。。
题意:分别给你两个杯子的容量 和水的体积,这个体积是要通过那两个杯子来实现,具体的实现方式有六种,分别是:
倒满1,2不动;倒满2,1不动;清空1,2不动;清空2,1不动;从1往2倒水;从2往1倒水。
所以我写了三个函数,通过所传参数的不同来实现对1还是对2的操作。
需要注意的一点是,在每个函数中都要对当前状态进行判断。。
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
const int inf = 99999999;
int a,b,c;
int s = 0,e = 0;
int vist[120][120];
struct node
{
int a,b;
int ans;
} q[inf];
void FULL (int x,int y,int t, int wz)
{
struct node f;
if (wz == 0)
{
f.a = a;
f.b = y;
}
if (wz == 1)
{
f.a = x;
f.b = b;
}
if (vist[f.a][f.b]==0)
{
f.ans = t + 1;
q[e++] = f;
vist[f.a][f.b] = 1;
}
}
void DROP (int x,int y,int t,int wz)
{
struct node f;
if (wz == 2)
{
f.a = 0;
f.b = y;
}
if (wz == 3)
{
f.a = x;
f.b = 0;
}
if (vist[f.a][f.b]==0)
{
f.ans = t + 1;
q[e++] = f;
vist[f.a][f.b] = 1;
}
}
void POUR (int x,int y,int t,int wz)
{
struct node f;
if (wz == 4)// x ->y
{
if (x + y <= b)
{
y = x + y ;
x = 0 ;
}
else
{
x = x + y - b;
y = b;
}
}
if (wz == 5)// y-> x
{
if (x + y <= a)
{
x = x + y ;
y = 0 ;
}
else
{
y = y + x -a;
x = a;
}
}
f.a = x;
f.b = y;
if (vist[f.a][f.b]==0)
{
f.ans = t + 1;
q[e++] = f;
vist[f.a][f.b] = 1;
}
}
void BFS ( )
{
struct node t,f;
t.a = 0;
t.b = 0;
t.ans = 0;
vist[t.a][t.b] = 1;
q[e++] = t;
while (s < e)
{
t = q[s++];
f = t;
if (t.a == c || t.b == c)
{
printf ("%d\n",t.ans);
return ;
}
for (int i=0; i<6; i++)
{
if (i==0) FULL (f.a,f.b,f.ans,i);
if (i==1) FULL (f.a,f.b,f.ans,i);
if (i==2) DROP (f.a,f.b,f.ans,i);
if (i==3) DROP (f.a,f.b,f.ans,i);
if (i==4) POUR (f.a,f.b,f.ans,i);
if (i==5) POUR (f.a,f.b,f.ans,i);
}
}
printf ("impossible\n");
}
int main()
{
while (~scanf ("%d%d%d",&a,&b,&c))
{
s=0,e=0;
memset (vist,0,sizeof (vist));
BFS ( );
}
return 0;
}