leetcode [399]Evaluate Division

Equations are given in the format A / B = k, where A and B are variables represented as strings, and k is a real number (floating point number). Given some queries, return the answers. If the answer does not exist, return -1.0.

Example:
Given a / b = 2.0, b / c = 3.0.
queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? .
return [6.0, 0.5, -1.0, 1.0, -1.0 ].

The input is: vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries , where equations.size() == values.size(), and the values are positive. This represents the equations. Return vector<double>.

According to the example above:

equations = [ ["a", "b"], ["b", "c"] ],
values = [2.0, 3.0],
queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ]. 

The input is always valid. You may assume that evaluating the queries will result in no division by zero and there is no contradiction.

题目大意:

给一系列表达式的值,查询某一表达式是否能以给定表达式的值求出。

解法:

根据表达式的值可以组成图,比如a/b=2,那么就是a到b存在边,且边上的权重为2,b到a也是存在边的,且权重为1/2.

java:

class Solution {
    private double dfs(String start,String end,Map<String,ArrayList<String>> pairs, Map<String, ArrayList<Double>> values, HashSet<String> set, double value){
        if (set.contains(start)) return 0.0;
        if (!pairs.containsKey(start)) return 0.0;
        if (start.equals(end)) return value;
        set.add(start);

        ArrayList<String> strList=pairs.get(start);
        ArrayList<Double> valueList=values.get(start);
        double tmp=0.0;
        for (int i=0;i<strList.size();i++){
            tmp=dfs(strList.get(i),end,pairs,values,set,value*valueList.get(i));
            if (tmp!=0){
                break;
            }
        }
        set.remove(start);

        return tmp;
    }

    public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
        Map<String,ArrayList<String>> pairs=new HashMap<>();
        Map<String,ArrayList<Double>> valuesPair=new HashMap<>();
        for (int i=0;i<equations.size();i++){
            pairs.computeIfAbsent(equations.get(i).get(0),k->new ArrayList<>()).add(equations.get(i).get(1));
            valuesPair.computeIfAbsent(equations.get(i).get(0),k->new ArrayList<>()).add(values[i]);
            pairs.computeIfAbsent(equations.get(i).get(1),k->new ArrayList<>()).add(equations.get(i).get(0));
            valuesPair.computeIfAbsent(equations.get(i).get(1),k->new ArrayList<>()).add(1/values[i]);
        }

        double[] res=new double[queries.size()];
        for (int i=0;i<queries.size();i++){
            res[i]=dfs(queries.get(i).get(0),queries.get(i).get(1),pairs,valuesPair,new HashSet<>(),1.0);
            if (res[i]==0.0) res[i]=-1.0;
        }

        return res;
    }
}

猜你喜欢

转载自www.cnblogs.com/xiaobaituyun/p/11109445.html
今日推荐