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.

问题分析

实际看完题目我们就能意识到这道题目其实就是给出起点终点求路径的问题。显然,这是一个有向图,如有 a/b = 4的两个顶点,则在图中建立a到b权值为4以及b到a权值为 1/4 的边,接着只需要按照提供的query查找相应的边并将边上的权值相乘即可。注意到题目中最后一句,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> > graph;
      vector<double> res;
      if (equations.empty()) return res;
      int tmp_s = equations.size();
      for (auto i = 0; i < tmp_s; ++i) {
        graph[equations[i].first].insert(make_pair(equations[i].second,values[i]));
        graph[equations[i].second].insert(make_pair(equations[i].first,1/values[i]));
      }

      for (auto i : queries) {
        visited.clear();
        int tmp = res.size();
        dfs(i.first, i.second, res, graph, 1);
        if (tmp == res.size()) res.push_back(-1.0);

      }
      return res;
    }
    set<string> visited;
    void dfs(string start, string end, vector<double> & res,unordered_map<string, unordered_map<string, double> > & graph, double  product) {
      visited.insert(start);
      if (start == end && graph.count(start)) {
        res.push_back(product);
         return;
      }
      for (auto i : graph[start]) {
        if (visited.find(i.first) == visited.end())
            dfs(i.first, end, res, graph, product * i.second);
      }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值