C++之set find结构体对象

这篇博客详细介绍了如何运用深度优先搜索(DFS)策略解决LeetCode中的365号问题——水壶问题。作者通过创建状态结构体和自定义排序函数,实现了状态的存储和比较,并在搜索过程中避免了重复状态。最后,通过递归地尝试所有可能的操作,如倒水、清空或填满水壶,来判断是否能测量出目标容量的水。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下面的例子作说明,leetcode中的365水壶问题:

class Solution {
public:
    struct status{
        int left;
        int right;
    };
class statusSort {
public:
	//重点
    bool operator() (const status &a, const status &b) const {
        if(a.left!=b.left)return a.left<b.left;
        else return a.right<b.right;
    }
};
    bool canMeasureWater(int jug1Capacity, int jug2Capacity, int targetCapacity) {
        stack<status>s;
        set<status,statusSort>st;
        s.push(status{0,0});
        while(!s.empty()){
            status temp=s.top();
            s.pop();
            int l=temp.left,r=temp.right;
            if(l==targetCapacity||r==targetCapacity||(l+r)==targetCapacity)return true;
            set<status,statusSort>::iterator it=st.find(temp);
            if(it!=st.end())continue;
            st.insert(temp);
            s.push(status{jug1Capacity,r});
            s.push(status{l,jug2Capacity});
            s.push(status{l,0});
            s.push(status{0,r});
            s.push(status{l-min(l,jug2Capacity-r),r+min(l,jug2Capacity-r)});
            s.push(status{l+min(r,jug1Capacity-l),r-min(r,jug1Capacity-l)});

        }
        return false;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值