除法求值 带权并查集 力扣399

除法求值题目

class Solution {
public:
    int find(int p, vector<int> &father, vector<double> & weight) 
    {
        if (father[p] != p) {
            int tf = father[p]; //保存原父节点
            father[p] = find(father[p], father, weight);
            weight[p] = weight[p] * weight[tf]; //更新权值
        }
        return father[p];
    }

    void merge(int a, int b, double w, vector<int> &father, vector<double> & weight)
    {
        int fa = find(a, father, weight);
        int fb = find(b, father, weight);
        if (fa == fb)
            return;

        father[fa] = b;
        weight[fa] = w / weight[a];
    }

    vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) 
    {
        unordered_map<string, int> points;
        int cnt = 0;

        for (auto item : equations) {
            if (points.find(item[0]) == points.end()) {
                points[item[0]] = cnt++;
            }
            if (points.find(item[1]) == points.end()) {
                points[item[1]] = cnt++;
            }
        }

        vector<int> father(cnt);
        vector<double> weight(cnt, 1.0);

        for (int i = 0; i < cnt; ++i) {
            father[i] = i;
        }

        for (int i = 0; i < equations.size(); ++i) {
            int a = points[equations[i][0]];
            int b = points[equations[i][1]];
            double w = values[i];
            merge(a, b, w, father, weight);
        }

        vector<double> ret;
        for (auto item : queries) {
            if (points.find(item[0]) == points.end() or points.find(item[1]) == points.end()) {
                ret.push_back(-1.0);
                continue;
            }
            int a = points[item[0]];
            int b = points[item[1]];
            int fa = find(a, father, weight), fb = find(b, father, weight);
            if (fa != fb) {
                ret.push_back(-1.0);
            }
            else {
                ret.push_back(weight[a] / weight[b]);
            }
        }

        for (int i = 0; i < cnt; ++i) {
            printf("%d %lf \n", father[i], weight[i]);
        }

        return ret;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值