中山大学算法课程题目详解(第五周)
来源:互联网 发布:我想学软件编程 编辑:程序博客网 时间:2024/06/07 05:51
问题描述:
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: double dfs(string from, string to, map<string, map<string, double>> &mp, set<string> & visited, double val){if (mp[from].count(to)) {return mp[from][to] * val;}for (pair<string, double>p : mp[from]) {string str = p.first;if (visited.count(str) == 0) {visited.insert(str);double cur = dfs(str, to, mp, visited, p.second * val);if (cur != -1.0) return cur;}}return -1.0;}vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {vector<double> result;map<string, map<string, double>> mp;int i = 0;for (pair<string, string> p : equations) {mp[p.first][p.second] = values[i];mp[p.second][p.first] = 1.0 / values[i];i++;}for (pair<string, string> p : queries) {if (mp.count(p.first) && mp.count(p.second)) {if (p.first == p.second) {result.push_back(1.0);continue;}else {set<string> visited;result.push_back(dfs(p.first, p.second, mp, visited, 1.0));}}else {result.push_back(-1.0);}}return result;}};
- 中山大学算法课程题目详解(第五周)
- 中山大学算法课程题目详解(第二周)
- 中山大学算法课程题目详解(第三周)
- 中山大学算法课程题目详解(第六周)
- 中山大学算法课程题目详解(第七周)
- 中山大学算法课程题目详解(第八周)
- 中山大学算法课程题目详解(第九周)
- 中山大学算法课程题目详解(第十周)
- 中山大学算法课程题目详解(第十二周)
- 中山大学算法课程题目详解(第一周)
- 中山大学算法课程题目详解(第四周)
- 中山大学算法课程题目详解(第十一周)
- 算法分析与设计课程作业第五周#1
- 中山大学软件学院的课程
- 中山大学软件学院的课程
- Ng机器学习课程第五周神经网络反向传播算法课后作业初学者的理解
- 中山大学信科院2011年复试题目
- 中山大学Sicily在线测评系统题目分类
- 子网掩码的概念
- Python3-3D plotting with Mayavi
- Android中static有关的内存泄漏
- BZOJ 3450 Tyvj1952 Easy 期望dp
- hdu 1247 Hat’s Words 字典树单词拼接
- 中山大学算法课程题目详解(第五周)
- [App] dnsmasq 安装
- 通用麻将胡牌算法
- tomcat启动时间少怎么办!
- ES6中Json、String、Map、Object之间的转换
- 【UVA10859】Placing Lampposts
- 网页被重新刷新(网址后面自动添加了?)
- ANSJ词性标注集
- 深入理解Java对象的创建过程:类的初始化与实例化