以下面的例子作说明,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;
}
};
|