365. 水壶问题

  1. 水壶问题
    有两个水壶,容量分别为 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tux~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值