C++ 里面set存儲結構體


題目鏈接:https://leetcode-cn.com/problems/water-and-jug-problem/

官方題解也超時了。。。

主要是看看set里面存儲結構體的方法吧

using PII = pair<int, int>;

class Solution {
public:
    bool canMeasureWater(int x, int y, int z) {
        stack<PII> stk;
        stk.emplace(0, 0);
        auto hash_function = [](const PII& o) -> hash<int>() {return (o.first) ^ hash<int>()(o.second);};
        unordered_set<PII, decltype(hash_function)> seen(0, hash_function);
        while (!stk.empty()) {
            if (seen.count(stk.top())) {
                stk.pop();
                continue;
            }
            seen.emplace(stk.top());
            
            auto [remain_x, remain_y] = stk.top();
            stk.pop();
            if (remain_x == z || remain_y == z || remain_x + remain_y == z) {
                return true;
            }
            // 把 X 壺灌滿。
            stk.emplace(x, remain_y);
            // 把 Y 壺灌滿。
            stk.emplace(remain_x, y);
            // 把 X 壺倒空。
            stk.emplace(0, remain_y);
            // 把 Y 壺倒空。
            stk.emplace(remain_x, 0);
            // 把 X 壺的水灌進 Y 壺,直至灌滿或倒空。
            stk.emplace(remain_x - min(remain_x, y - remain_y), remain_y + min(remain_x, y - remain_y));
            // 把 Y 壺的水灌進 X 壺,直至灌滿或倒空。
            stk.emplace(remain_x + min(remain_y, x - remain_x), remain_y - min(remain_y, x - remain_x));
        }
        return false;
    }
};

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM