倒水问题

题目:

        设大、中、小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;
}


 

   

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值