您的位置:首页 > 其它

倒水问题

2015-11-06 10:58 302 查看
题目:

        设大、中、小3个杯子的容量分别为a,b,c,最初只有大杯子装满水,其他两个杯子为空。最少需要多少步才能让某一个杯子中的水有x升呢?你需要打印出每步操作后各个杯子中的水量(0 < c < b < a < 1000)。

 

分析:经典的BFS

#include <stdio.h>
#include <iostream>
using namespace std;
const int maxn = 100005;

int a, b, c, x;

struct node
{
int f;
int a, b, c;
};
node p[maxn];

void print(node w)
{
if (w.f != -1)
print(p[w.f]);

printf("%d %d %d\n", w.a, w.b, w.c);
}

void get(int &x, int &y, int m)
{
int sub = m - y;
if (x >= sub)
{
x -= sub;
y = m;
}
else
{
y += x;
x = 0;
}
}

node pour(node t, int op)
{
switch(op)
{
case 0:
{
get(t.a, t.b, b);
return t;
}
case 1:
{
get(t.a, t.c, c);
return t;
}
case 2:
{
get(t.b, t.c, c);
return t;
}
case 3:
{
get(t.b, t.a, a);
return t;
}
case 4:
{
get(t.c, t.a, a);
return t;
}
case 5:
{
get(t.c, t.b, b);
return t;
}
}
}

void bfs()
{
int head, end;
p[head = end = 0].a = a;
p[head].b = 0;
p[head].c = 0;
p[end++].f = -1;

while (head < end)
{
node w = p[head];

if (w.a == x || w.b == x || w.c == x)
{
print(w);
break;
}

node t;

t = pour(w, 0);
t.f = head;
p[end++] = t;

t = pour(w, 1);
t.f = head;
p[end++] = t;

t = pour(w, 2);
t.f = head;
p[end++] = t;

t = pour(w, 3);
t.f = head;
p[end++] = t;

t = pour(w, 4);
t.f = head;
p[end++] = t;

t = pour(w, 5);
t.f = head;
p[end++] = t;

++head;
}
}

int main()
{
while (scanf("%d %d %d %d", &a, &b, &c, &x) == 4)
{
bfs();
}

return 0;
}


 

   

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: