Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
- map<string, int> m;
- int count = 0;
- for(auto edge: equations){
- if(!m.count(edge[0]))
- m[edge[0]] = count++;
- if(!m.count(edge[1]))
- m[edge[1]] = count++;
- }
- double dp[count][count];
- for(int i=0; i<count; i++)
- for(int j=0; j<count; j++){
- if(i == j)
- dp[i][j] = 1.0;
- else
- dp[i][j] = -1.0;
- }
- for(int i=0; i<equations.size(); i++){
- int x = m[equations[i][0]];
- int y = m[equations[i][1]];
- double val = values[i];
- dp[x][y] = val;
- dp[y][x] = 1.0/val;
- }
- for(int k=0; k<count; k++)
- for(int i=0; i<count; i++)
- for(int j=0; j<count; j++){
- if(dp[i][k] != -1.0 && dp[k][j] != -1.0)
- dp[i][j] = dp[i][k]*dp[k][j];
- }
- vector<double> ans;
- for(auto q: queries){
- if(m.count(q[0]) && m.count(q[1])){
- int x = m[q[0]];
- int y = m[q[1]];
- ans.push_back(dp[x][y]);
- }
- else
- ans.push_back(-1.0);
- }
- return ans;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement