Pots(待完善)
Pots SDUT
题目是 有 两个桶 分别为A升 B升 , 通过多次的六种操作, 得到 C升水
求出最少操作步数。利用BFS 的特点(涟漪效应,可以求最短路)
BFS遍历 图:(此图来自 jack cui, https://cuijiahua.com/blog/2018/01/alogrithm_10.html)
#include<stdio.h>
#include<string.h>
int book[1005][1005];//标记改点已经被遍历
struct Queque
{
int x, y;//x 表示 A中的 量 ,y 表示 B中的量
int step;
} Q[1000005]; //队列
int head, tail;
void BFS(int a, int b, int n)
{
//初始化操作
memset(book, 0, sizeof(book));
memset(map, 0,sizeof(map));
head = 0;
tail = 0;
// 0 0 入队
Q[tail].x = 0;
Q[tail++].y = 0;
Q[head].step = 0;
book[0][0] = 1;
while(head != tail)// BFS 主要部分
{
struct Queque t = Q[head++];//出队
if(t.x == n|| t.y == n)// 如果 a或 b 中有n 升水
{
printf("%d\n", t.step);//输出操作步数
return ;//结束
}
int i;
for(i = 0; i < 6; i++)// 六种操作
{
if(i == 0)// fill a
{
if(book[a][t.y] == 0)
{
book[a][t.y] = 1;//标记
Q[tail].x = a;// 入队
Q[tail].y = t.y;
Q[tail++].step = t.step+1;
}
}
if(i == 1)// fill b
{
if(book[t.x][b] == 0)
{
book[t.x][b] = 1;
Q[tail].x = t.x;
Q[tail].y = b;
Q[tail++].step = t.step+1;
}
}
if(i == 2)// empty a
{
if(book[0][t.y] == 0)
{
book[0][t.y] = 1;
Q[tail].x = 0;
Q[tail].y = t.y;
Q[tail++].step = t.step+1;
}
}
if(i == 3)// empty b
{
if(book[t.x][0] == 0)
{
book[t.x][0] = 1;
Q[tail].x = t.x;
Q[tail].y = 0;
Q[tail++].step = t.step+1;
}
}
if(i == 4)// pour a b
{
struct Queque f;
f.y = t.x+t.y;
if(f.y < b&&book[0][f.y] == 0)
{
book[0][f.y] = 1;
Q[tail].y = f.y;
Q[tail].x = 0;
Q[tail++].step = t.step+1;
}
else if(f.y >= b && book[f.y- b][b] == 0)
{
book[f.y - b][b] = 1;
Q[tail].x = f.y - b;
Q[tail].y = b;
Q[tail++].step = t.step+1;
}
}
if(i == 5)// pour b a
{
struct Queque f ;
f.x = t.x+t.y;
if(f.x < a&& book[f.x][0] == 0)
{
book[f.x][0] = 1;
Q[tail].x = f.x;
Q[tail].y = 0;
Q[tail++].step = t.step+1;
}
else if(f.x >= a && book [a][f.x - a] == 0)
{
book[a][f.x - a] = 1;
Q[tail].x = a;
Q[tail].y = f.x - a;
Q[tail++].step = t.step+1;
}
}
}
}
printf("impossible\n");// 如果达不到 目的 输出 impossible
}
int main ()
{
int a, b, n;
while(~scanf("%d %d %d", &a, &b, &n))
{
BFS(a, b, n);
}
return 0;
}
/***************************************************
User name:
Result: Accepted
Take time: 80ms
Take Memory: 2492KB
Submit time: 2019-02-28 16:41:58
****************************************************/