leetcode题解:第399题Evaluate Division

https://leetcode-cn.com/problems/evaluate-division/

文章目录

      • 分析
      • 解法一、图遍历
        • 代码
      • 解法二、并查集
        • 代码

分析

这道题的目的很明确,逻辑也容易理解,人可以很容易地计算出这种方程式的结果,但怎么把这种方程式在程序中表示是一个难题。换言之,正确地表示方程式,就能把这个看似难处理的问题转换成容易解决的问题。

解法一、图遍历

如果给出提示,把这题与联系起来,能否快速找到解决办法呢?
我们可以很自然地想到,可以用带权图来表示输入的所有方程式:a / b = value表示两条边:a->b,权重为valueb->a,权重为1.0 / value。对于查询的问题方程式x / y,问题即可转换为在这个带权图中查找从xy的一条路径,并计算路径上的权重乘积。

几个编码细节

  1. 如何选择图的表示方法?邻接表
    节点astring类型,所以得用哈希表来存储节点a到其所有边的映射;用vector来存储所有由a指向的节点,即从a出去的边的集合
  2. 如何表示带权重的边?结构体
    一条加权边除了要具备所指向的节点,还需要有权重,因此定义一个结构体是很好的选择
  3. 如何找从xy的路径?BFSDFS
    老生常谈的话题了,只是需要注意存储权重的乘积以及不要遍历已经遍历过的节点。

代码

class Solution {
     
public:
    struct edge {
     
        string node;
        double weight;
        edge (string node, double weight): node(node), weight(weight) {
     }
    };
    
    vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
     
        unordered_map<string, vector<edge>> edges;
        int n = equations.size();
        // 构造无向带权图
        for (int i = 0; i < n; ++i) {
     
            string x = equations[i][0], y = equations[i][1];
            edges[x].push_back(edge(y, values[i]));
            edges[y].push_back(edge(x, 1 / values[i]));
        }
        vector<double> ans;
        for (auto& query : queries) {
     
            string x = query[0], y = query[1];
            bool flag = false;
            // 图里是否存在从x到y的一条路径
            unordered_map<string, int> used;
            queue<pair<string, double>> q;
            if (edges.count(x)) {
     
                q.push({
     x, 1.0});
                used[x] = 1;
            }
            while (!q.empty()) {
     
                auto [node, weight] = q.front();
                q.pop();
                if (node == y) {
     
                    ans.push_back(weight);
                    flag = true;
                    break;
                }
                for (edge& e : edges[node]) {
     
                    if (used[e.node] == 0) {
     
                        q.push({
     e.node, weight * e.weight});
                        used[e.node] = 1;
                    }
                }
            }
            // 不存在则query无解
            if (!flag) ans.push_back(-1.0);
        }
        return ans;
    }
};

解法二、并查集

构建带权重边的并查集,对于要计算的方程式x / y

  1. 如果xy不在一个联通的子集中,无解
  2. 否则,分别计算x / rooty / root,从而求解x / y

要实现这样的并查集,需要定义两个变量:parents[a]代表存在a / parents[a],值为weights[a]

代码

class Solution {
     
public:
    unordered_map<string, string> parents; // 存在a / parents[a]
    unordered_map<string, double> weights; // weights[a]: a / parents[a]

    pair<string, double> MyFind(string& x) {
     
        if (!parents.count(x)) return {
     "", -1.0};
        double weight = 1.0;
        while (x != parents[x]) {
     
            weight *= weights[x];
            x = parents[x];
        }
        return {
     x, weight}; //x最终为root, weight代表x / root的值
    }

    void MyUnion(string& a, string& b, double value) {
     
        pair<string, double> root1 = MyFind(a);
        pair<string, double> root2 = MyFind(b);
        if (root1.first == root2.first) return;
        parents[root1.first] = root2.first;
        // root1.second: a / root1, value: a / b, root2.second: b / root2
        weights[root1.first] = 1.0 / root1.second * value * root2.second;
    }

    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 x = equations[i][0], y = equations[i][1];
            // 初始化
            if (!parents.count(x)) parents[x] = x, weights[x] = 1.0;
            if (!parents.count(y)) parents[y] = y, weights[y] = 1.0;
            MyUnion(x, y, values[i]);
        }
        vector<double> ans;
        for (auto& query : queries) {
     
            string x = query[0], y = query[1];
            pair<string, double> root1 = MyFind(x);
            pair<string, double> root2 = MyFind(y);
            if (root1.first != root2.first || root1.first == "" || root2.first == "") ans.push_back(-1.0);
            else ans.push_back(root1.second / root2.second);
        }
        return ans;
    }
};

你可能感兴趣的:(算法)