399. 除法求值
1 class Solution 2 { 3 public: 4 vector<double> calcEquation(vector<vector<string>> &equations, vector<double> &values, vector<vector<string>> &queries) 5 { 6 unordered_map<string, unordered_map<string, double >> weight; 7 for (int i = 0; i < equations.size(); i++) 8 { 9 weight[equations[i][0]][equations[i][1]] = values[i]; 10 weight[equations[i][1]][equations[i][0]] = 1. / values[i]; 11 } 12 vector<double> res; 13 for (auto query:queries) 14 { 15 res.push_back(bfs(query[0], query[1], weight)); 16 } 17 return res; 18 } 19 20 double bfs(string start, string end, unordered_map<string, unordered_map<string, double >> weight) 21 { 22 if (weight.count(start) == 0 || weight.count(end) == 0) 23 return -1; 24 queue<pair<string, double >> que; 25 unordered_set<string> visited; 26 visited.insert(start); 27 que.push(make_pair(start, 1.0)); 28 while (!que.empty()) 29 { 30 int size = que.size(); 31 for (int i = 0; i < size; i++) 32 { 33 auto node = que.front(); 34 que.pop(); 35 if (node.first == end) 36 return node.second; 37 for (auto mid:weight[node.first]) 38 { 39 if (visited.count(mid.first) == 0) 40 { 41 visited.insert(mid.first); 42 que.push(make_pair(mid.first, node.second * mid.second));//没找到就一层层往下乘 43 } 44 } 45 } 46 } 47 return -1; 48 } 49 };
Mamba never out

浙公网安备 33010602011771号