leetcode 365

class Solution {
public:
    int gcd(int a,int b){
        if(a%b==0)return b;
        return gcd(b,a%b);
    }
    bool canMeasureWater(int x, int y, int z) {
        if(z==0) return true;
        if(x==0) return y==z;
        if(y==0) return x==z;

        int a=max(x,y);
        // 两个杯子放不下的话
        if(x+y<z)
         return false;
        int b=min(x,y);
        return z%gcd(a,b)==0;
    }
};
class Solution {
    pair<int, int> op(int type, const pair<int, int> &state, int x, int y) {
        // state 记录的是两个杯子中动态的水量,x,y 表示杯子的容量是固定的
        switch(type) {
            case 0 : return make_pair(x, state.second);//装
            case 2 : return make_pair(state.first, y);
            case 1 : return make_pair(0, state.second);
            case 4 : return make_pair(state.first, 0);
            // A倒入B,如果B中剩余的多余A,则把A 倒入,否则的话只能把B装满
            case 5 :{
                int move = min(state.first, y-state.second);
                return make_pair(state.first - move, state.second + move);
            }
            case 3 : {
                int move = min(x-state.first, state.second);
                return make_pair(state.first + move, state.second - move);
            }
        }
        return make_pair(x,y);//这个不影响
    }
    struct HashPair {
        size_t operator()(const pair<int, int> &key) const noexcept
	    {
		    return size_t(key.first)*100000007 + key.second;
	    }
    };
public:
    bool canMeasureWater(int x, int y, int z) {
        unordered_set<pair<int,int>, HashPair> mark;
        queue<pair<int,int>> q;
        // q.push(make_pair(0,0));
        q.push(make_pair(x,y));//初始装态不影响正确性
        while(q.empty() == false) {
            auto f = q.front();
            q.pop();
            if(f.first + f.second == z) {
                return true;
            }
            // 两个杯子中状态只出现一次
            for(int i = 0; i < 6; i++) {
                auto next = op(i, f, x, y);
                if(mark.find(next) != mark.end()) {
                    continue;
                }
                mark.insert(next);
                q.push(next);
            }
        }
        return false;
    }
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值