题目描述
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.
输入
There are multiple test cases.
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
题目大意
有两个罐子分别是AB体积,通过三种操作把在这两个罐中产生一个有C体积水的罐子,找出最短的操作数
think
两个罐子一共有六种操作,我们可以用数字分别代表这六种操作,然后利用bfs计数输出
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct node
{
int x, y, num;
}q[10001], f, t;
int vir[101][101];
int bfs(int a, int b, int c)
{
t.x = 0;
t.y = 0;
t.num = 0;
int front = 0, rear = 0;
q[rear++] = t;
vir[t.x][t.y] = 1;
while(front<rear)
{
t = q[front++];//取出首元素判断操作
if(t.x==c||t.y==c)
{
printf("%d\n", t.num);
return 0;
}
for(int i = 0;i<6;i++)//六种情况
{
if(i==0)//B装满
{
f.x = t.x;//
f.y = b;
}
if(i==1)//A装满
{
f.x = a;
f.y = t.y;//
}
if(i==2)//A倒出
{
f.x = 0;
f.y = t.y;
}
if(i==3)//B倒出
{
f.x = t.x;
f.y = 0;
}
if(i==4)//B倒给A
{
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)//A倒给B
{
f.x = f.y - b;
f.y = b;
}
else
{
f.x = 0;
}
}
if(vir[f.x][f.y]==0)
{
vir[f.x][f.y] = 1;
f.num = t.num + 1;
q[rear++] = f;//先+1再压栈
}
}
}
printf("impossible\n");
return 0;
}
int main()
{
int a, b, c;
while(~scanf("%d %d %d", &a, &b, &c))
{
memset(vir, 0, sizeof(vir));
bfs(a, b, c);
}
return 0;
}
/***************************************************
User name: jk180140刘洋
Result: Accepted
Take time: 0ms
Take Memory: 248KB
Submit time: 2019-01-18 09:46:13
****************************************************/