-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy path1514. Path with Maximum Probability1
29 lines (29 loc) · 1.16 KB
/
1514. Path with Maximum Probability1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public:
double maxProbability(int n, vector<vector<int>>& edges, vector<double>& succProb, int start_node, int end_node) {
vector<vector<pair<int, double>>> adj(n);
vector<double> dist(n, 0); // Initialize distance/probability array with 0
// Build the adjacency list
for (int i = 0; i < edges.size(); i++) {
int u = edges[i][0], v = edges[i][1];
adj[u].emplace_back(v, succProb[i]);
adj[v].emplace_back(u, succProb[i]);
}
priority_queue<pair<double, int>> pq;
pq.push({1, start_node}); // Start with probability 1 for the start node
dist[start_node] = 0; // Probability to reach start node is 1
while (!pq.empty()) {
auto [prob, node] = pq.top(); pq.pop();
if (node == end_node)
return prob;
for (auto& [neighbor, cost] : adj[node]) {
double newProb = prob * cost;
if (newProb > dist[neighbor]) {
dist[neighbor] = newProb;
pq.push({newProb, neighbor});
}
}
}
return 0;
}
};