作者:
sep
,
2022-07-02 15:30:54
,
所有人可见
,
阅读 6
class Solution {
public:
int n = 0;
double temp;
double g[30][30];
bool vis[30];
unordered_map<string, int> hash;
int getID(string a) {
if (!hash.count(a)) hash[a] = n ++;
return hash[a];
}
vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
for (int i = 0; i < equations.size(); i ++ ) {
int a = getID(equations[i][0]), b = getID(equations[i][1]);
g[a][b] = values[i], g[b][a] = 1 / values[i];
}
vector<double> res;
for (auto& t : queries) {
string a = t[0], b = t[1];
if (!hash.count(a) || !hash.count(b)) res.push_back(-1);
else {
memset(vis, 0, sizeof vis);
if (dfs(getID(a), getID(b), 1)) res.push_back(temp);
else res.push_back(-1);
}
}
return res;
}
bool dfs(int u, int b, double m) {
if (u == b) {
temp = m;
return true;
}
vis[u] = true;
for (int i = 0; i < n; i ++ ) {
if (g[u][i] != 0 && !vis[i])
if (dfs(i, b, m * g[u][i]))
return true;
}
return false;
}
};