class Solution {
public:
vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
unordered_set<string> vertices;
unordered_map<string, unordered_map<string, double>> edges;
for (int i = 0; i < equations.size(); i++) {
string a = equations[i][0], b = equations[i][1];
double var = values[i];
edges[a][b] = var, edges[b][a] = 1 / var;
vertices.insert(a), vertices.insert(b);
}
for (const string& k : vertices) {
for (const string& i : vertices) {
for (const string& j : vertices) {
if (edges[i][k] && edges[j][k])
edges[i][j] = edges[i][k] * edges[k][j];
}
}
}
vector<double> res;
for (vector<string>& q : queries) {
string a = q[0], b = q[1];
if (edges[a][b]) res.push_back(edges[a][b]);
else res.push_back(-1);
}
return res;
}
};