美文网首页
Evaluate Division

Evaluate Division

作者: 我叫胆小我喜欢小心 | 来源:发表于2017-05-16 14:26 被阅读11次

    题目来源
    给一堆等式,求另一堆等式的值。
    用并查集来做,然后我不熟悉,边看讨论区边写的…写完觉得实际上也不难,就是看着有点长而已。
    代码如下:

    class Solution {
    public:
        vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {
            unordered_map<string, Node*> maps;
            vector<double> res;
            for (int i=0; i<equations.size(); i++) {
                string s1 = equations[i].first, s2 = equations[i].second;
                if (maps.count(s1) == 0 && maps.count(s2) == 0) {
                    maps[s1] = new Node();
                    maps[s2] = new Node();
                    maps[s2]->value = 1;
                    maps[s1]->value = values[i];
                    maps[s2]->parent = maps[s1];
                }
                else if (maps.count(s1) == 0) {
                    maps[s1] = new Node();
                    maps[s1]->value = maps[s2]->value * values[i];
                    maps[s1]->parent = maps[s2];
                }
                else if (maps.count(s2) == 0) {
                    maps[s2] = new Node();
                    maps[s2]->value = maps[s1]->value / values[i];
                    maps[s2]->parent = maps[s1];
                }
                else {
                    unionNode(maps[s1], maps[s2], values[i], maps);
                }
            }
            
            for (auto query : queries) {
                if (maps.count(query.first) == 0 || maps.count(query.second) == 0 || 
                findParent(maps[query.first]) != findParent(maps[query.second]))
                    res.push_back(-1);
                else
                    res.push_back(maps[query.first]->value / maps[query.second]->value);
            }
            return res;
        }
        
    private:
        struct Node {
            Node* parent;
            double value = 0;
            Node() {parent = this;}
        };
        
        void unionNode(Node* node1, Node* node2, double num, unordered_map<string, Node*>& maps)
        {
            Node* parent1 = findParent(node1), *parent2 = findParent(node2);
            double ratio = node2->value * num / node1->value;
            for (auto it=maps.begin(); it!=maps.end(); it++)
                if (findParent(it->second) == parent1)
                    it->second->value *= ratio;
            parent1->parent = parent2;
        }
        
        Node* findParent(Node* node)
        {
            if (node->parent == node)
                return node;
            node->parent = findParent(node->parent);
            return node->parent;
        }
    };
    

    相关文章

      网友评论

          本文标题:Evaluate Division

          本文链接:https://www.haomeiwen.com/subject/gcslxxtx.html