题目描述:
主要思路:
本题主要利用并查集的思想,重点是要弄明白分子和分母的指向关系以及一系列的值的变化规则。
查询时如果两个数字不在一个集合里那么结果就为-1.
class Solution {
public:unordered_map<string,string> f;unordered_map<string,double> num;string find(string k){if(f[k]==k)return k;string kk=f[k];f[k]=find(f[k]);num[k]*=num[kk];return f[k];}vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {int n=equations.size();for(int i=0;i<n;++i){string a=equations[i][0],b=equations[i][1];double x=values[i];if(f.find(a)==f.end()&&f.find(b)==f.end()){f[a] = b;f[b] = b;num[b] = 1.0;num[a] = x;}else if(f.find(a)==f.end()){f[a] = b;num[a] = x;}else if(f.find(b)==f.end()){f[b] = b;num[b] = 1.0;string ap=find(a);f[ap] = b;num[ap] = x/num[a];}else{string ap=find(a),bp=find(b);if(ap==bp)continue;f[ap] = f[bp];num[ap] = num[b]*x/num[a];}}vector<double> ans;for(auto x:queries){string a=x[0],b=x[1];if(f.find(a)==f.end()||f.find(b)==f.end()||find(a)!=find(b))ans.push_back(-1.0);elseans.push_back(num[a]/num[b]);}return ans;}
};