Advertisement
nikunjsoni

399-2

Apr 29th, 2021
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     map<string, int> m;
  4.     double result;
  5.     void dfs(int source, int dest, vector<vector<pair<int, double>>> &graph, vector<bool> &vis, double res){
  6.         if(source == dest) result = res;
  7.         vis[source] = true;
  8.         for(auto child: graph[source]){
  9.             if(!vis[child.first]){
  10.                 dfs(child.first, dest, graph, vis, res*child.second);
  11.             }
  12.         }
  13.         vis[source] = false;
  14.     }
  15.    
  16.     vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
  17.         vector<vector<pair<int, double>>> graph(40);
  18.         int count = 0;
  19.        
  20.         // Make the graph.
  21.         for(int i=0; i<equations.size(); i++){
  22.             auto &edge = equations[i];
  23.             if(!m.count(edge[0]))
  24.                 m[edge[0]] = count++;
  25.             if(!m.count(edge[1]))
  26.                 m[edge[1]] = count++;
  27.             int from = m[edge[0]], to = m[edge[1]];
  28.             double val = values[i];
  29.             graph[from].push_back({to, val});
  30.             graph[to].push_back({from, 1.0/val});
  31.         }
  32.        
  33.         // Making self loops.
  34.         for(int i=0; i<count; i++)
  35.             graph[i].push_back({i, 1.0});
  36.        
  37.         // For each query do dfs from source to destination.
  38.         vector<double> ans;
  39.         vector<bool> vis(count, false);
  40.         for(auto q: queries){
  41.             if(m.count(q[0]) && m.count(q[1])){
  42.                 int x = m[q[0]];
  43.                 int y = m[q[1]];
  44.                 result = -1.0;
  45.                 dfs(x, y, graph, vis, 1.0);
  46.                 ans.push_back(result);
  47.             }
  48.             else
  49.                 ans.push_back(-1.0);
  50.         }
  51.         return ans;
  52.     }
  53. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement