Advertisement
nikunjsoni

399-1

Apr 29th, 2021
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.47 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
  4.         map<string, int> m;
  5.         int count = 0;
  6.         for(auto edge: equations){
  7.             if(!m.count(edge[0]))
  8.                 m[edge[0]] = count++;
  9.             if(!m.count(edge[1]))
  10.                 m[edge[1]] = count++;
  11.         }
  12.         double dp[count][count];
  13.         for(int  i=0; i<count; i++)
  14.             for(int j=0; j<count; j++){
  15.                 if(i == j)
  16.                     dp[i][j] = 1.0;
  17.                 else
  18.                     dp[i][j] = -1.0;
  19.             }
  20.         for(int i=0; i<equations.size(); i++){
  21.             int x = m[equations[i][0]];
  22.             int y = m[equations[i][1]];
  23.             double val = values[i];
  24.             dp[x][y] = val;
  25.             dp[y][x] = 1.0/val;
  26.         }
  27.        
  28.         for(int k=0; k<count; k++)
  29.             for(int i=0; i<count; i++)
  30.                 for(int j=0; j<count; j++){
  31.                     if(dp[i][k] != -1.0 && dp[k][j] != -1.0)
  32.                         dp[i][j] = dp[i][k]*dp[k][j];
  33.                 }
  34.        
  35.         vector<double> ans;
  36.         for(auto q: queries){
  37.             if(m.count(q[0]) && m.count(q[1])){
  38.                 int x = m[q[0]];
  39.                 int y = m[q[1]];
  40.                 ans.push_back(dp[x][y]);
  41.             }
  42.             else
  43.                 ans.push_back(-1.0);
  44.         }
  45.         return ans;
  46.     }
  47. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement