classSolution{public:struct HashPair {
size_t operator()(const pair<int,int>&key)constnoexcept{returnsize_t(key.first)*100000007+ key.second;}};boolcanMeasureWater(int x,int y,int z){
queue<pair<int,int>> q;
unordered_set<pair<int,int>, HashPair> s;//初始状态0,0 目标状态x+y==z
q.push(make_pair(0,0));
s.insert(make_pair(0,0));while(!q.empty()){
pair<int,int> temp = q.front();
q.pop();if(temp.first + temp.second == z or temp.first == z or temp.second == z)returntrue;for(int i =0; i <6; i++){auto next =generate(i, temp, x, y);if(s.find(next)!= s.end()){continue;}
s.insert(next);
q.push(next);}}returnfalse;}
pair<int,int>generate(int i, pair<int,int>&state,int x,int y){switch(i){case0:returnmake_pair(x, state.second);case1:returnmake_pair(state.first, y);case2:returnmake_pair(0, state.second);case3:returnmake_pair(state.first,0);case4:{//x倒入y中if(state.first + state.second < y){returnmake_pair(0, state.first + state.second);}else{returnmake_pair(state.first + state.second - y, y);}}case5:{//y倒入x中if(state.first + state.second < x){returnmake_pair(state.first + state.second,0);}else{returnmake_pair(x, state.first + state.second - x);}}}returnmake_pair(0,0);}};
数学 贝祖定理:ax+by=z 有解当且仅当 z是 x,y 的最大公约数的倍数。
classSolution{public:boolcanMeasureWater(int x,int y,int z){if(x + y < z)returnfalse;if(x ==0|| y ==0)return z ==0|| x + y == z;return z %gcd(x, y)==0;}};