中级农民
- 积分
- 217
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-11-30
- 最后登录
- 1970-1-1
|
399. Evaluate Division
第三遍写这道题,用时21分钟,有3个syntax error和1个sematic error
花了8分钟修改错误,然后AC
syntax error:
1. 在应该assign的地方写了return
2. unordered_map passed by const reference的时候不能用[ ]访问,要用iterator访问(map[key]->second)
3. double 写错成了 string
semantic error:
1. 在查querie的时候遇到from == dst的case时没有检查from是否存在于图中,如果不存在的话,应该返回-1,但是我的程序忘记检查这一项,返回了1,是错的。
延伸:
还有union find的解,但是我对union find不是很熟练,所以不想写了。我知道这样不对,但是我就是做不到现在花时间研究union find解法,因为目前意志力不够强。
不过我要在看一遍union find的视频,掌握其思路。
- class Solution {
- public:
- vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {
- /* 0.MISC */
-
- /* 1. prep */
- vector<double> answer;
- auto graph = BuildGraph(equations, values);
-
- /* 2. key algo */
- for(auto query: queries){
- string from = query.first, dst = query.second;
- double ansElement = 1.0;
-
- if(from == dst && graph.find(from) != graph.end())ansElement = 1.0;
- else if(graph.find(from) == graph.end() || graph.find(dst) == graph.end())ansElement = -1.0;
- else{
- double ratio = RatioBFS(graph, from, dst);
- ansElement = ratio;
- }
-
- answer.emplace_back(ansElement);
- }
-
- /* 3. answer */
- return answer;
- }
-
- double
- RatioBFS(const unordered_map<string, vector< pair<string, double> > > & graph,
- const string& from, const string& dst){
- /* 0. MISC */
-
- /* 1. prep */
- queue<pair<string, double> > bfsQueue;
- unordered_set<string> visited;
-
- bfsQueue.emplace(from, 1.0);
- visited.emplace(from);
-
- /* 2. key algo */
- while(!bfsQueue.empty()){
- auto node = bfsQueue.front(); bfsQueue.pop();
- auto nodeName = node.first;
- auto nodeRatio = node.second;
-
- for(auto child: graph.find(nodeName)->second){
- string childName = child.first;
- double relativeRatio = child.second;
-
- if(visited.find(childName) != visited.end())continue;
- visited.emplace(childName);
-
- double childRatio = nodeRatio * relativeRatio;
- if(childName == dst)return childRatio;
-
- bfsQueue.emplace(childName, childRatio);
- }
- }
-
- /* 3. answer */
- return -1;
- }
-
- unordered_map<string, vector< pair<string, double> > >
- BuildGraph( const vector<pair<string, string>> equations,
- const vector<double>& values){
- /* 0. MISC */
-
- /* 1. prep */
- unordered_map<string, vector< pair<string, double> > > graph;
-
- /* 2. key algo */
- for(int i = 0; i < equations.size(); ++i){
- string from = equations[i].first, dst = equations[i].second;
- double ratio = values[i];
- graph[from].emplace_back(dst, ratio);
- graph[dst].emplace_back(from, 1/ratio);
- }
-
- /* 3. answer */
- return graph;
-
- }
- };
复制代码
补充内容 (2018-12-10 05:45):
如果是上白板写这道题,85行代码还是太长,需要舍弃一些。我是这样安排的,先写最核心的BFS部分,再写query的部分,最后写BuildGraph. |
|