起因
程设期末复习 -> 第三周课件 -> 隐式图问题 -> 倒水问题
代码
#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进行广度优先搜索;