399. Evaluate Division

56 篇文章 0 订阅
8 篇文章 0 订阅


题目

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.

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.

题意分析

就是给你一些等式, 通过这些等式计算查询等式的结果.
由于是除法, 所以如果给了a/b, 也会有b/a
本质上就是查看图中某两点是否存在一条路径, 如果存在, 返回路径权值乘积

解答

思路

先建好图, 然后对图做DFS, 并且在查询过程中记录值的大小

实现

class Solution {
public:
    vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {
        map = new HashMap();

        // build map 
        for (int i = 0; i < equations.length; i++) {
            string[] e = equations[i];
            if (!map.containsKey(e[0]))
                map.put(e[0], new ArrayList());
            map.get(e[0]).add(new VandE(e[1], values[i]));

            if (!map.containsKey(e[1]))
                map.put(e[1], new ArrayList());
            map.get(e[1]).add(new VandE(e[0], 1 / values[i]));
        }

        double[] result = new double[queries.length];
        for (int i = 0; i < result.length; i++) {
            result[i] = dfs(queries[i][0], queries[i][1], 1, new HashSet());
        }
        return result;

    }

    hash_map<string, list<VandE> > map;

    bool dfs(string begin, string end, double result, set<string> visited) {
        if (visited.contains(begin)) return -1;
        if (!map.containsKey(begin)) return -1;

        if (begin.equals(end)) return value;
        visited.add(begin);
        for (VandE adj : map.get(begin)) {
            double res = dfs(adj.divisor, end, value * adj.val, visited);
            if (res != -1) return res;
        }

        visited.remove(begin);
        return -1;        
    }

    class VandE {
        String divisor;
        double val;
        Info(String d, double v) { this.divisor = d; this.val = v; }
    }

};

但是由于LeetCode不支持hash_map, 所以不使用hash_map, 用回unordered_map:

class Solution {
public:
    vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> query) {
        unordered_map<string,unordered_map<string, double>> map;
        vector<double> result;

        // build graph
        for (int i = 0; i < values.size(); ++i) {
            map[equations[i].first].insert(make_pair(equations[i].second, values[i]));
            //if(values[i]!=0)
            map[equations[i].second].insert(make_pair(equations[i].first, 1 / values[i]));
        }

        for (auto i : query) {
            unordered_set<string> visited;
            double tmp = dfs(i.first, i.second, map, visited);
            if(tmp) result.push_back(tmp);
            else result.push_back(-1);
        }
        return result;
    }

    double dfs(string start, string end, unordered_map<string,unordered_map<string, double>> &map, unordered_set<string> &visited) {
        if(map[start].find(end) != map[start].end()) return map[start][end]; // found path between(start, end)

        for (auto adj : map[start]) {
            if(visited.find(adj.first) == visited.end()) {  // not yet visited
                visited.insert(adj.first);
                double tmp = dfs(adj.first, end, map, visited);
                if(tmp) return adj.second * tmp;
            }
        }
        return 0;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值