Evaluate Division

Equations are given in the format A / B = k, where A and B are variables represented as strings, and k is a real number (floating point number). Given some queries, return the answers. If the answer does not exist, return -1.0.

Example:
Given a / b = 2.0, b / c = 3.0. 
queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? . 
return [6.0, 0.5, -1.0, 1.0, -1.0 ].

The input is: vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries , where equations.size() == values.size(), and the values are positive. This represents the equations. Return vector<double>.

According to the example above:

equations = [ ["a", "b"], ["b", "c"] ],
values = [2.0, 3.0],
queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ]. 

The input is always valid. You may assume that evaluating the queries will result in no division by zero and there is no contradiction.

/*
class Solution {
public:
    vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {
        unordered_map<string, unordered_map<string, double>> m;
        vector<double> res;
        for (int i = 0; i < values.size(); ++i) {
            m[equations[i].first].insert(make_pair(equations[i].second, values[i]));
            if (values[i])
                m[equations[i].second].insert(make_pair(equations[i].first, 1 / values[i]));
        }
        
        for (auto i : queries) {
            unordered_set<string> s;
            double tmp = check(i.first, i.second, m, s);
            if (tmp) res.push_back(tmp);
            else res.push_back(-1.0);
        }
        return res;
    }
    
    double check(string up, string down, unordered_map<string, unordered_map<string, double>>& m, unordered_set<string>& s) {
        if (m[up].find(down) != m[up].end()) return m[up][down];
        for (auto i : m[up]) {
            if (s.find(i.first) == s.end()) {
                s.insert(i.first);
                double tmp = check(i.first, down, m, s);
                if (tmp) return tmp * i.second;
            }
        }
        return 0;
    }
};
*/
//------------ Another method -------------
class Solution {
public:
    vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {
        unordered_map<string, Node*> m;
        vector<double> res;
        for(int i = 0; i < values.size(); ++i) {
            string s0 = equations[i].first, s1 = equations[i].second;
            if (m.count(s0) == 0 && m.count(s1) == 0) { //s0 and s1 are both not in m
                m[s0] = new Node(values[i]);
                m[s1] = new Node(1.0);
                m[s1]->parent = m[s0];
            }
            else if (m.count(s0) == 0) {    //only s0 not in m
                m[s0] = new Node(m[s1]->value * values[i]);
                m[s0]->parent = m[s1];
            }
            else if (m.count(s1) == 0) {    //only s1 not in m
                m[s1] = new Node(m[s0]->value / values[i]);
                m[s1]->parent = m[s0];
            }    
            else //s0 and s1 are both in m
                unionNodes(m[s0], m[s1], values[i], m);
        }

        for (auto i : queries) {
            if (m.count(i.first) == 0 || m.count(i.second) == 0 || findParent(m[i.first]) != findParent(m[i.second]))
                res.push_back(-1.0);
            else
                res.push_back(m[i.first]->value / m[i.second]->value);
        }
        return res;
    }
    
private:
    struct Node {
        Node* parent;
        double value;
        Node(double num) : parent(this), value(num) {}
    };
    
    void unionNodes(Node* node0, Node* node1, double num, unordered_map<string, Node*>& m) {
        Node* parent0 = findParent(node0), *parent1 = findParent(node1);
        double ratio = node1->value * num / node0->value;
        for (auto it = m.begin(); it != m.end(); ++it)
            if (findParent(it->second) == parent0)
                it->second->value *= ratio;
        parent1 -> parent = parent0;
    }
    
    Node* findParent(Node* node) {
        if (node->parent == node) return node;
        node->parent = findParent(node->parent);
        return node->parent;
    }
};
9 lines "Floyd–Warshall" in Python

class Solution(object):
    def calcEquation(self, equations, values, queries):
        """
        :type equations: List[List[str]]
        :type values: List[float]
        :type queries: List[List[str]]
        :rtype: List[float]
        """
        quot = collections.defaultdict(dict)
        for (num, den), val in zip(equations, values):
            quot[num][num] = quot[den][den] = 1.0
            quot[num][den], quot[den][num] = val, 1 / val
        for k, i, j in itertools.permutations(quot, 3):
            if k in quot[i] and j in quot[k]:
                quot[i][j] = quot[i][k] * quot[k][j]
        return [quot[num].get(den, -1.0) for num, den in queries]



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值