编程语言
首页 > 编程语言> > 图相关算法

图相关算法

作者:互联网

Floyd求解除法运算

给你一个变量对数组 equations 和一个实数值数组 values 作为已知条件,其中 equations[i] = [Ai, Bi] 和 values[i] 共同表示等式 Ai / Bi = values[i] 。每个 Ai 或 Bi 是一个表示单个变量的字符串。
另有一些以数组 queries 表示的问题,其中 queries[j] = [Cj, Dj] 表示第 j 个问题,请你根据已知条件找出 Cj / Dj = ? 的结果作为答案。
返回 所有问题的答案 。如果存在某个无法确定的答案,则用 -1.0 替代这个答案。如果问题中出现了给定的已知条件中没有出现的字符串,也需要用 -1.0 替代这个答案。
注意:输入总是有效的。你可以假设除法运算中不会出现除数为 0 的情况,且不存在任何矛盾的结果。

示例1:

输入:equations = [[“a”,“b”],[“b”,“c”]], values = [2.0,3.0], queries = [[“a”,“c”],[“b”,“a”],[“a”,“e”],[“a”,“a”],[“x”,“x”]]
输出:[6.00000,0.50000,-1.00000,1.00000,-1.00000]
解释:
条件:a / b = 2.0, b / c = 3.0
问题:a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ?
结果:[6.0, 0.5, -1.0, 1.0, -1.0 ]

示例2:

输入:equations = [[“a”,“b”],[“b”,“c”],[“bc”,“cd”]], values = [1.5,2.5,5.0], queries = [[“a”,“c”],[“c”,“b”],[“bc”,“cd”],[“cd”,“bc”]]
输出:[3.75000,0.40000,5.00000,0.20000]

class Solution {
    /**
    思路分析:
        Floyd算法求解
            1 先构建图
            2 Floyd构建关系
            3 解决问题
     */
    public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
        // 1 处理equations,给字符串加上索引
        int index = 0;
        Map<String, Integer> map = new HashMap<>();
        for(List<String> list : equations){
            for(String s : list){
                if(!map.containsKey(s)){
                    map.put(s, index++);
                }
            }
        }
        double[][] grap = new double[index + 1][index + 1];
        for(String s : map.keySet()){
            int k = map.get(s);
            grap[k][k] = 1.0;
        }
        index = 0;
        // 2 构建图
        for(List<String> list : equations){
            String a = list.get(0);
            String b = list.get(1);
            int aIndex = map.get(a);
            int bIndex = map.get(b);
            grap[aIndex][bIndex] = values[index];
            grap[bIndex][aIndex] = 1 / values[index++];
        }
        // 3 Floyd构建求解关系
        for(int i = 0; i < grap.length; i++){
            for(int j = 0; j < grap.length; j++){
                for(int k = 0; k < grap.length; k++){
                    if(k == j || grap[j][k] != 0){
                        continue;
                    }
                    grap[j][k] = grap[j][i] * grap[i][k];
                }
            }
        }
        double[] res = new double[queries.size()];
        index = 0;
        // 4 解决问题
        for(List<String> list : queries){
            String a = list.get(0);
            String b = list.get(1);
            if(map.containsKey(a) && map.containsKey(b)){
                int aIndex = map.get(a);
                int bIndex = map.get(b);
                res[index++] = grap[aIndex][bIndex] == 0.0 ? -1.0 : grap[aIndex][bIndex];
            }else{
                res[index++] = -1.0;
            }
        }
        return res;
    }
}

标签:index,get,grap,list,map,int,算法,相关
来源: https://blog.csdn.net/shao1996/article/details/119061725