地里新农-请到考试中心学习规则
- 积分
- 0
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-1-28
- 最后登录
- 1970-1-1
|
看了解释后直接写一次性跑通
- public void addEdge(String sa, String sb, double val, Map<String, Map<String, Double>> graph) {
- Map<String, Double> vertex = graph.get(sa);
- if (vertex == null) {
- vertex = new HashMap<>();
- graph.put(sa, vertex);
- }
- vertex.put(sb, val);
- }
- public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
- Map<String, Map<String, Double>> graph = new HashMap<>();
- for (int i = 0; i < values.length; i++) {
- String[] syms = equations[i];
- String sym1 = syms[0];
- String sym2 = syms[1];
- addEdge(sym1, sym2, values[i], graph);
- addEdge(sym2, sym1, 1 / values[i], graph);
- }
- double[] rt = new double[queries.length];
- for (int i = 0;i < queries.length; i++) {
- String[] syms = queries[i];
- String sym1 = syms[0];
- String sym2 = syms[1];
- Map<String, Double> vertexA = graph.get(sym1);
- rt[i] = -1;
- if (vertexA == null) {
- continue;
- }
- rt[i] = countRatio(graph, sym1, sym2, new HashSet<>());
- }
- return rt;
- }
- private double countRatio(Map<String, Map<String, Double>> graph, String syma, String symb, Set<String> visited) {
- Map<String, Double> vertex = graph.get(syma);
- visited.add(syma);
- if (vertex == null) return -1;
- if (syma.equals(symb)) return 1;
- for (Map.Entry<String, Double> e : vertex.entrySet()) {
- String sb = e.getKey();
- Double ratio = e.getValue();
- if (!visited.contains(sb)) {
- double cr = countRatio(graph, sb, symb, visited);
- if (cr != -1) {
- double res = ratio * cr;
- if (visited.contains(symb)) return res;
- }
- }
- }
- return -1;
- }
复制代码 |
|