隐式图经典问题_倒水问题(C++)

起因

程设期末复习 -> 第三周课件 -> 隐式图问题 -> 倒水问题

代码

#include <bits/stdc++.h>
using namespace std;
queue<pair<int, int>> q;		//record to check state
set<pair<int,int>> his_state;	//record history state
int cap_a, cap_b, target;		//capacity of a and b,and the target

void init()
{
	cin >> cap_a >> cap_b >> target;
	q.push(make_pair(0, 0));	//Assume the initial size 0,0
	his_state.emplace(0, 0);
}

bool bfs()
{
	while (!q.empty())
	{
		pair<int, int> now = q.front();
		q.pop();
		int cur_a = now.first, cur_b = now.second;//current state of a and b
		
		//state transition
		//state A->B   first:a  second:b
		pair<int, int> a_b,b_a;
		if (cur_a + cur_b > cap_b) a_b = make_pair(cur_a + cur_b - cap_b, cap_b);
		else a_b = make_pair(0, cur_a + cur_b);
		if (cur_a + cur_b > cap_a) b_a = make_pair(cap_a, cur_a + cur_b - cap_a);
		else b_a = make_pair(cur_a + cur_b, 0);

		//one for one :A->B,B->A,A->zeor,A->full,B->zero,B->full
		int temp_a[6] = { a_b.first,b_a.first,0,cap_a,cur_a,cur_a };
		int temp_b[6] = { a_b.second,b_a.second,cur_b,cur_b,0,cap_b };

		for (int i = 0; i < 6; i++)
		{
			//if the state has been recorded
			if (his_state.find(make_pair(temp_a[i], temp_b[i])) == his_state.end())
				continue;

			q.push(make_pair(temp_a[i], temp_b[i]));
			his_state.emplace(make_pair(temp_a[i], temp_b[i]));

			//if hit the target  return true
			if (temp_a[i] == target || temp_b[i] == target)
				return true;
		}
	}
	//if not return false
	return false;
}

int main()
{
	init();					//initialize
	if (bfs())
		cout << "Y" << endl;
	else
		cout << "F" << endl;
	return 0;
}

分析

所谓隐式图,就是很难看出来这实际上是个图(大佬除外).
整体采用BFS广度优先搜索
对于倒水问题,我们先规定一次只能操作一个杯子,对每一种状态分析其后续操作,获得操作后的次状态,后续分析获得的这些次状态,重复上述过程;
分析其状态的转移(节点的后续节点):

  • 将杯子A中的水全部倒入B中(倒满为止)
  • 将杯子B中的水全部倒入A中(倒满为止)
  • 将A中的水全部倒出,B不变
  • 将A中的水盛满,B不变
  • 将B中的水全部倒出,A不变
  • 将B中的水盛满,A不变

对每种状态都获取其后续的六种状态,通过利用一个set记录曾经出现过的状态
将新的状态入队,进行后续的搜索.

乱七八糟的总结

对于隐式图问题,一定要搞清楚获取一个状态后其后续的状态如何转移/获取;
如何通过BFS进行广度优先搜索;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值