leetcode 399除法求值 超水带权并查集

在这里插入图片描述
题目

class Solution {
   
public:
    int f[45];
    double multi[45];
    map<string,int>hash;int tot=0;
    int seek(int x){
   
        if(x==f[x]) return x;
        int fa=f[x];
        f[x]=seek(fa);
        multi[x]*=multi[fa];
        return f[x];
    }
    vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
   
        for(int i=0;i<equations.size();++i){
   
            vector<string> vec=equations[i];
            if(!hash.count(vec[0])) hash[vec[0]]=++tot,f[tot]=tot,multi[tot]=1.0;
            if(!hash.count(vec[1])) hash[vec[1]]=++tot,f[tot]=tot,multi[tot]=1.0;
        }
        for(int i=0;i<equations.size();++i){
   
            vector<string> vec=equations[i];
            int x=hash[vec[0]],y=hash[vec[1]];
            int rx=seek(x),ry=seek(y);
            if(rx==ry) continue;
            f[rx]=ry,multi[rx]=values[i]*multi[y]/multi[x];
        }
        vector<double>ans;
        for(int i=0;i<queries.size();++i){
   
            if(!hash.count(queries[i][0])||!hash.count(queries[i][1])) ans.push_back(-1);
            else{
   
                int x=hash[queries[i][0]],y=hash[queries[i][1]];
                int rx=seek(x),ry=seek(y);
                if(rx!=ry) ans.push_back(-1);
                else ans.push_back(multi[x]/(multi[y]*multi[rx]));
            }
        }
        return ans;
    }
};

相关推荐

  1. LeetCode 399除法(图的bfs遍历)

    2024-01-19 16:38:05       51 阅读
  2. (基础+以及可撤销后期更新)

    2024-01-19 16:38:05       35 阅读
  3. LeetCode399触发

    2024-01-19 16:38:05       34 阅读
  4. 除法[中等]

    2024-01-19 16:38:05       44 阅读
  5. leetcode

    2024-01-19 16:38:05       35 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-19 16:38:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-19 16:38:05       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-19 16:38:05       82 阅读
  4. Python语言-面向对象

    2024-01-19 16:38:05       91 阅读

热门阅读

  1. ffmpeg命令整理

    2024-01-19 16:38:05       43 阅读
  2. 数组练习 Leetcode 66.加一

    2024-01-19 16:38:05       60 阅读
  3. C#设计模式教程(2):工厂方法模式

    2024-01-19 16:38:05       48 阅读
  4. Jtti:电影服务器的带宽和存储空间怎么选择?

    2024-01-19 16:38:05       55 阅读
  5. python文件移动的方法

    2024-01-19 16:38:05       49 阅读
  6. 队列和栈相关例题

    2024-01-19 16:38:05       51 阅读
  7. lodash 的 _.groupBy 函数是怎么实现的?

    2024-01-19 16:38:05       49 阅读
  8. Redis面试题22

    2024-01-19 16:38:05       56 阅读
  9. vue2-ace-editor实现一个简单的代码编辑器

    2024-01-19 16:38:05       50 阅读
  10. 快速了解Docker(概念+基本组成)

    2024-01-19 16:38:05       59 阅读