- 水壶问题
有两个水壶,容量分别为 jug1Capacity 和 jug2Capacity 升。水的供应是无限的。确定是否有可能使用这两个壶准确得到 targetCapacity 升。
如果可以得到 targetCapacity 升水,最后请用以上水壶中的一或两个来盛放取得的 targetCapacity 升水。
你可以:
装满任意一个水壶
清空任意一个水壶
从一个水壶向另外一个水壶倒水,直到装满或者倒空
示例 1:
输入: jug1Capacity = 3, jug2Capacity = 5, targetCapacity = 4
输出: true
解释:来自著名的 “Die Hard”
示例 2:
输入: jug1Capacity = 2, jug2Capacity = 6, targetCapacity = 5
输出: false
示例 3:
输入: jug1Capacity = 1, jug2Capacity = 2, targetCapacity = 3
输出: true
==================================
这道题就是我们常见的两个水壶是否能乘出需要的容积。
用的图的深度优先,由一种状态可以转移到另一种状态,深度查找就行了。总之就是遍历。
不过这道题我就是看了题解也错了一块,计算一个桶向另一个桶倒入的时候错了,就是最后几行那些min啥的。
#include <stdc++.h>
using namespace std;
class node {
public:
int x_;
int y_;
node(int x, int y) : x_(x), y_(y) {}
bool operator==(const node& p) const { return x_ == p.x_ && y_ == p.y_; }
};
struct hash_func {
size_t operator()(const node& p) const {
return std::hash<int>()(p.x_) ^ std::hash<int>()(p.y_);
}
};
unordered_set<node, hash_func> used;
stack<node> a;
int zz;
bool node_judge(const node& nodetmp) {
if (nodetmp.x_ == zz || nodetmp.x_ + nodetmp.y_ == zz || nodetmp.y_ == zz)
return true;
if (used.find(nodetmp) == used.end()) {
used.insert(nodetmp);
a.push(nodetmp);
}
return false;
}
bool canMeasureWater(int x1, int y1, int z) {
bool ret = false;
a.push({0, 0});
zz = z;
if (z == 0) return true;
while (!a.empty()) {
auto x = a.top().x_, y = a.top().y_;
a.pop();
if (node_judge(node(0, y)) || node_judge(node(x, 0)) ||
node_judge(node(x1, y)) || node_judge(node(x, y1)) ||
node_judge(node(x-min(x,y1-y),y+min(x,y1-y))) ||//<将x倒向y
node_judge(node(x+min(y,x1-x),y-min(y,x1-x))))
return true;
}
return ret;
}
int main() {
cout << boolalpha << canMeasureWater(104597, 104623, 123) << endl;
return 0;
}