Untitled
unknown
plain_text
a year ago
1.4 kB
2
Indexable
Never
class Solution { public: double bfs(unordered_map<string,vector<pair<string,double>>>&adj,string src,string tar){ if(adj.find(src) ==adj.end() || adj.find(tar) ==adj.end()) return -1.0; queue<pair<string,double>> q; //current node,product unordered_set<string> vis; q.push({src,1.0}); vis.insert(src); while(!q.empty()){ pair<string,double> p=q.front(); q.pop(); string node=p.first; double dist=p.second; if(node==tar) return dist; for(auto nbr:adj[node]){ if(vis.find(nbr.first)==vis.end()){ q.push({nbr.first,dist * nbr.second}); vis.insert(nbr.first); } } } return -1.0; } vector<double> calcEquation(vector<vector<string>>& eq, vector<double>& values, vector<vector<string>>& que) { //making adjlist unordered_map<string,vector<pair<string,double>>> adj; for(int i=0;i<eq.size();i++){ string a=eq[i][0]; string b=eq[i][1]; adj[a].push_back({b,values[i]}); adj[b].push_back({a,1/values[i]}); } vector<double> ans; for(auto i:que){ double x=bfs(adj,i[0],i[1]); ans.push_back(x); } return ans; } };