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:

  1. equations = [ ["a", "b"], ["b", "c"] ],
  2. values = [2.0, 3.0],
  3. 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.

这道题作为第四次编程比赛的压轴题,感觉还是挺有难度的,个人感觉难度应该设为hard比较合理。这道题已知条件中给了一些除法等式,然后给了另外一些除法等式,问我们能不能根据已知条件求出结果,不能求出来的用-1表示。问题本身是很简单的数学问题,但是写代码来自动实现就需要我们用正确的数据结构和算法,通过观察题目中的例子,我们可以看出如果需要分析的除法式的除数和被除数如果其中任意一个没有在已知条件中出现过,那么返回结果-1,所以我们在分析已知条件的时候,可以使用set来记录所有出现过的字符串,然后我们在分析其他除法式的时候,可以使用递归来做。通过分析得出,不能直接由已知条件得到的情况主要有下面三种:

1) 已知: a / b = 2, b / c = 3, 求 a / c
2) 已知: a / c = 2, b / c = 3, 求 a / b
3) 已知: a / b = 2, a / c = 3, 求 b / c

虽然有三种情况,但其实后两种情况都可以转换为第一种情况,对于每个已知条件,我们将其翻转一下也存起来,那么对于对于上面美中情况,就有四个已知条件了:

1) 已知: a / b = 2,b / a = 1/2,b / c = 3,c / b = 1/3,求 a / c
2) 已知: a / c = 2,c / a = 1/2,b / c = 3,c / b = 1/3,求 a / b
3) 已知: a / b = 2,b / a = 1/2a / c = 3,c / a = 1/3,求 b / c

我们发现,第二种和第三种情况也能转化为第一种情况,只需将上面加粗的两个条件相乘即可。对于每一个需要解析的表达式,我们需要一个HashSet来记录已经访问过的表达式,然后对其调用递归函数。在递归函数中,我们在HashMap中快速查找该表达式,如果跟某一个已知表达式相等,直接返回结果。如果没有的话,那么就需要间接寻找了,我们在HashMap中遍历跟解析式中分子相同的已知条件,跳过之前已经遍历过的,否则就加入visited数组,然后再对其调用递归函数,如果返回值是正数,则乘以当前已知条件的值返回,就类似上面的情况一,相乘以后b就消掉了。如果已知找不到解,最后就返回-1,参见代码如下:

解法一:

  1. class Solution {
  2. public:
  3. vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {
  4. vector<double> res;
  5. for (int i = ; i < equations.size(); ++i) {
  6. m[equations[i].first][equations[i].second] = values[i];
  7. m[equations[i].second][equations[i].first] = 1.0 / values[i];
  8. }
  9. for (auto query : queries) {
  10. unordered_set<string> visited;
  11. double t = helper(query.first, query.second, visited);
  12. res.push_back((t > 0.0) ? t : -);
  13. }
  14. return res;
  15. }
  16. double helper(string up, string down, unordered_set<string>& visited) {
  17. if (m[up].count(down)) return m[up][down];
  18. for (auto a : m[up]) {
  19. if (visited.count(a.first)) continue;
  20. visited.insert(a.first);
  21. double t = helper(a.first, down, visited);
  22. if (t > 0.0) return t * a.second;
  23. }
  24. return -1.0;
  25. }
  26.  
  27. private:
  28. unordered_map<string, unordered_map<string, double>> m;
  29. };

此题还有迭代的写法,用邻接列表的表示方法建立了一个图,然后进行bfs搜索,需要用queue来辅助运算,参见代码如下:

解法二:

  1. class Solution {
  2. public:
  3. vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {
  4. vector<double> res;
  5. unordered_map<string, unordered_map<string, double>> g;
  6. for (int i = ; i < equations.size(); ++i) {
  7. g[equations[i].first].emplace(equations[i].second, values[i]);
  8. g[equations[i].first].emplace(equations[i].first, 1.0);
  9. g[equations[i].second].emplace(equations[i].first, 1.0 / values[i]);
  10. g[equations[i].second].emplace(equations[i].second, 1.0);
  11. }
  12. for (auto query : queries) {
  13. if (!g.count(query.first) || !g.count(query.second)) {
  14. res.push_back(-1.0);
  15. continue;
  16. }
  17. queue<pair<string, double>> q;
  18. unordered_set<string> visited{query.first};
  19. bool found = false;
  20. q.push({query.first, 1.0});
  21. while (!q.empty() && !found) {
  22. for (int i = q.size(); i > ; --i) {
  23. auto t = q.front(); q.pop();
  24. if (t.first == query.second) {
  25. found = true;
  26. res.push_back(t.second);
  27. break;
  28. }
  29. for (auto a : g[t.first]) {
  30. if (visited.count(a.first)) continue;
  31. visited.insert(a.first);
  32. a.second *= t.second;
  33. q.push(a);
  34. }
  35. }
  36. }
  37. if (!found) res.push_back(-1.0);
  38. }
  39. return res;
  40. }
  41. };

参考资料:

https://leetcode.com/problems/evaluate-division/

https://leetcode.com/problems/evaluate-division/discuss/88347/c-bfs-solution-easy-to-understand

https://leetcode.com/problems/evaluate-division/discuss/88287/esay-understand-java-solution-3ms

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Evaluate Division 求除法表达式的值的更多相关文章

  1. [LeetCode] 399. Evaluate Division 求除法表达式的值

    Equations are given in the format A / B = k, where A and B are variables represented as strings, and ...

  2. pat02-线性结构3. 求前缀表达式的值(25)

    02-线性结构3. 求前缀表达式的值(25) 时间限制 400 ms 内存限制 65536 kB 代码长度限制 8000 B 判题程序 Standard 算术表达式有前缀表示法.中缀表示法和后缀表示法 ...

  3. PTA笔记 堆栈模拟队列+求前缀表达式的值

    基础实验 3-2.5 堆栈模拟队列 (25 分) 设已知有两个堆栈S1和S2,请用这两个堆栈模拟出一个队列Q. 所谓用堆栈模拟队列,实际上就是通过调用堆栈的下列操作函数: int IsFull(Sta ...

  4. 信息竞赛进阶指南--递归法求中缀表达式的值,O(n^2)(模板)

    // 递归法求中缀表达式的值,O(n^2) int calc(int l, int r) { // 寻找未被任何括号包含的最后一个加减号 for (int i = r, j = 0; i >= ...

  5. 【Zhejiang University PATest】02-3. 求前缀表达式的值

    算术表达式有前缀表示法.中缀表示法和后缀表示法等形式.前缀表达式指二元运算符位于两个运算数之前,例如2+3*(7-4)+8/4的前缀表达式是:+ + 2 * 3 - 7 4 / 8 4.请设计程序计算 ...

  6. openjduge 求简单表达式的值

    表达式求值 总时间限制:  10000ms  单个测试点时间限制:  1000ms  内存限制:  131072kB 给定一个只包含加法和乘法的算术表达式,请你编程计算表达式的值. 输入 输入仅有一行 ...

  7. K:双栈法求算术表达式的值

    相关介绍:  该算法用于求得一个字符串形式的表达式的结果.例如,计算1+1+(3-1)*3-(21-20)/2所得的表达式的值,该算法利用了两个栈来计算表达式的值,为此,称为双栈法,其实现简单且易于理 ...

  8. 3-07. 求前缀表达式的值(25) (ZJU_PAT数学)

    题目链接:http://pat.zju.edu.cn/contests/ds/3-07 算术表达式有前缀表示法.中缀表示法和后缀表示法等形式.前缀表达式指二元运算符位于两个运算数之前,比如2+3*(7 ...

  9. Leetcode: Evaluate Division

    Equations are given in the format A / B = k, where A and B are variables represented as strings, and ...

随机推荐

  1. 【分布式】Zookeeper与Paxos

    一.前言 在学习了Paxos在Chubby中的应用后,接下来学习Paxos在开源软件Zookeeper中的应用. 二.Zookeeper Zookeeper是一个开源的分布式协调服务,其设计目标是将那 ...

  2. 在mongoose中使用$match对id失效的解决方法

    Topic.aggregate( //{$match:{_id:"5576b59e192868d01f75486c"}}, //not work //{$match:{title: ...

  3. WCF学习系列汇总

    最近在学习WCF,打算把一整个系列的文章都”写“出来,包括理论和实践,这里的“写”是翻译,是国外的大牛写好的,我只是搬运工外加翻译.翻译的不好,大家请指正,谢谢了.如果觉得不错的话,也可以给我点赞,这 ...

  4. iOS 原生HTTP POST请求上传图片

    今天项目里做一个上传图片等个人信息的时候,使用了第三方AFNetworking - (AFHTTPRequestOperation *)POST:(NSString *)URLString param ...

  5. Xcode7.1环境下上架iOS App到AppStore 流程① (Part 一)

    前言部分 之前App要上架遇到些问题到网上搜上架教程发现都是一些老的版本的教程 ,目前iTunesConnect 都已经迭代好几个版本了和之前的 界面风格还是有很大的差别的,后面自己折腾了好久才终于把 ...

  6. django入门之模板的用法

    1.为什么要使用模板? 看下以前的代码 #-*- coding:utf-8 -*- from django.shortcuts import render from django.http impor ...

  7. 以ZeroMQ谈消息中间件的设计【译文】

    本文主要是探究学习比较流行的一款消息层是如何设计与实现的 ØMQ是一种消息传递系统,或者乐意的话可以称它为"面向消息的中间件".它在金融服务,游戏开发,嵌入式系统,学术研究和航空航 ...

  8. 如何采用easyui tree编写简单角色权限代码

    首先每个管理员得对应一个角色: 而角色可以操作多个栏目,这种情况下我们可以采用tree多选的方式: 在页面上js代码: $('#Permission').dialog({ title: '栏目权限', ...

  9. ES6之解构赋值

    截止到ES6,共有6种声明变量的方法,分别是var .function以及新增的let.const.import和class: 我们通常的赋值方法是: var foo='foo'; function ...

  10. Github装(zao)逼(jia)指(da)南(fa)

    Github之于工程师,类似于微博相册之于嫩模,像是个门面. 无论是晋升答辩,还是求职面试,有一个丰富的代码仓库不敢说好处有多大,但总归是有的.并且好处不局限于此,代码开源才会暴露问题才会改正,并且会 ...