java: add «1514. Path with Maximum Probability»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
601c8144e2
commit
b907b58d85
1 changed files with 57 additions and 0 deletions
57
java/path-with-maximum-probability.java
Normal file
57
java/path-with-maximum-probability.java
Normal file
|
@ -0,0 +1,57 @@
|
|||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.PriorityQueue;
|
||||
|
||||
class Solution {
|
||||
private record Edge(int v, double p) {}
|
||||
|
||||
private static Map<Integer, List<Edge>> makeGraph(int[][] edges, double[] p) {
|
||||
Map<Integer, List<Edge>> graph = new HashMap<>();
|
||||
|
||||
for (int i = 0; i < edges.length; ++i) {
|
||||
var u = edges[i][0];
|
||||
var v = edges[i][1];
|
||||
var prob = p[i];
|
||||
|
||||
graph.computeIfAbsent(u, k -> new ArrayList<>()).add(new Edge(v, prob));
|
||||
graph.computeIfAbsent(v, k -> new ArrayList<>()).add(new Edge(u, prob));
|
||||
}
|
||||
|
||||
return graph;
|
||||
}
|
||||
|
||||
private record Entry(double probability, int u) {}
|
||||
|
||||
public double maxProbability(
|
||||
int n, int[][] edges, double[] succProb, int startNode, int endNode) {
|
||||
var graph = makeGraph(edges, succProb);
|
||||
var maxProb = new double[n];
|
||||
|
||||
PriorityQueue<Entry> q =
|
||||
new PriorityQueue<>(Comparator.comparingDouble(Entry::probability).reversed());
|
||||
|
||||
maxProb[startNode] = 1;
|
||||
q.add(new Entry(maxProb[startNode], startNode));
|
||||
|
||||
while (!q.isEmpty()) {
|
||||
var candidate = q.poll();
|
||||
if (candidate.u() == endNode) {
|
||||
return candidate.probability();
|
||||
}
|
||||
|
||||
for (var edge : graph.getOrDefault(candidate.u(), new ArrayList<>())) {
|
||||
var possibleProbability = candidate.probability() * edge.p();
|
||||
|
||||
if (possibleProbability > maxProb[edge.v()]) {
|
||||
maxProb[edge.v()] = possibleProbability;
|
||||
q.add(new Entry(maxProb[edge.v()], edge.v()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue