题目里需要注意的:
1:分子和分母都是小写字母组成的长度小于5的字符串。
2:这道题中[“x”,“x”]等于-1.0而不是常人理解的1.0,因为x在equations中没有出现过。
题目特点:由于比值具有传递性,所以用带权的并查集来做。
具体细节:
并查集的初始化:所有节点的权值设置为1.0.
并查集的合并:先路径压缩!!!,u到v的权值 * v的权值=fau的权值 * u的权值,更新fau的权值。
并查集的查找:更新u的权值,u的权值=fau更新后的权值*u原来的权值
class Solution {
public:
void myunion(string u, string v, double val) {
string fau = find(u);
string fav = find(v);
weight[fau] = weight[v] * val / weight[u]; //
if (fau != fav) ump[fau] = fav;
}
string find(string s) {
if (s == ump[s]) return ump[s];
string father = ump[s]; //
ump[s] = find(ump[s]);
weight[s] *= weight[father]; //
return ump[s];
}
unordered_map<string, string> ump;
unordered_map<string, double> weight;
vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
for (auto& each : equations) {
ump[each[0]] = each[0];
ump[each[1]] = each[1];
weight[each[0]] = 1.0;
weight[each[1]] = 1.0;
}
int n = equations.size();
for (int i = 0; i < n; ++i) {
myunion(equations[i][0], equations[i][1], values[i]);
}
vector<double> ans;
for (auto& each : queries) {
if (!ump.count(each[0]) || !ump.count(each[1])) {
ans.push_back(-1.0);
continue;
}
string fau = find(each[0]); //
string fav = find(each[1]);
if (fau == fav) {
ans.push_back(weight[each[0]] / weight[each[1]]);
}
else ans.push_back(-1.0);
}
return ans;
}
};
由于计算queries数组时,判断在不在一个集合时,就已经对路径进行了压缩,所以直接用weight的值比即可。