原题:
有两个容量分别为 x升 和 y升 的水壶以及无限多的水。请判断能否通过使用这两个水壶,从而可以得到恰好 z升 的水?
如果可以,最后请用以上水壶中的一或两个来盛放取得的 z升 水。
你允许:
- 装满任意一个水壶
- 清空任意一个水壶
- 从一个水壶向另外一个水壶倒水,直到装满或者倒空
示例 1: (From the famous "Die Hard" example)
输入: x = 3, y = 5, z = 4 输出: True
示例 2:
输入: x = 2, y = 6, z = 5 输出: False
参照的实现代码:
#include "pch.h"
#include <stack>
#include <iostream>
#include <unordered_set>
#include <queue>
//#include <math.h>
using namespace std;
using PII = pair<int, int>;
//定义哈希函数 lambda表达式
auto hash_func = [](const PII& po) {return hash<int>()(po.first) ^ hash<int>()(po.second); };
class Solution {
public:
struct Hash_pair
{
size_t operator()(const PII& pi)const noexcept//noexcept,以前的throw(),不会抛出异常
{
return (size_t)(pi.first * 10001 )+ pi.second;
}
};
PII operation(int state, const PII& cur_state, int x, int y)
{
PII tmp;
int imin;
switch (state)
{
//倒满
case 0: tmp = make_pair(x, cur_state.second); break;
case 1: tmp = make_pair(cur_state.first, y); break;
//倒空
case 2: tmp = make_pair(0, cur_state.second); break;
case 3: tmp = make_pair(cur_state.first, 0); break;
//互倒
case 4: imin = min(cur_state.first, y - cur_state.second);//x倒满y,需要的是x和倒满y中的最小值
tmp = make_pair(cur_state.first- imin, cur_state.second + imin); break;
case 5: //把 Y 壶的水灌进 X 壶,直至灌满或倒空
imin = min(x - cur_state.first, cur_state.second);
tmp = make_pair(cur_state.first+ imin, cur_state.second- imin); break;
}
return tmp;
}
bool canMeasureWater(int x, int y, int z) {
//保存已存在过的
unordered_set<PII, decltype(hash_func)> unset(0,hash_func);// (0, hash_func);
// unordered_set<PII, decltype(hash_func)> unset;//err, 这里unordered_set的默认构造函数,需要调用自定义的哈希函数,需要unset(0,hash_func)
//来传入哈希函数
// unordered_set<PII, Hash_pair> unset;
queue<PII> que;
que.push(make_pair(0, 0));
while (!que.empty())
{
PII tmp = que.front();
que.pop();
if (tmp.first + tmp.second == z)
{
return true;
}
//unset.insert(make_pair(tmp.first, tmp.second));
//各种可操作情况
for (int i = 0; i < 6; i++)
{
PII pi = operation(i, tmp, x, y);
//已经存在过的情况
if (unset.find(pi) != unset.end())
continue;
unset.insert(pi);//加入set
que.push(pi);
}
}
return false;
}
};
int main()
{
int x, y, z;
while (true)
{
cin >> x;
cin >> y;
cin >> z;
if (z < 0 || y < 0 || x < 0) break;
Solution sl;
bool bl = sl.canMeasureWater(x, y, z);
string str = bl ? "true" : "false";
cout << str.c_str() << endl;
}
system("pause");
return 0;
}