From 7c60dee83b436e8e8a667bf9f191beced8de4fc3 Mon Sep 17 00:00:00 2001 From: Jack Sangdahl Date: Mon, 10 Mar 2025 00:36:13 -0600 Subject: chore: move cpp and rust code to directory --- other/path_max_probability.cpp | 52 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 other/path_max_probability.cpp (limited to 'other/path_max_probability.cpp') diff --git a/other/path_max_probability.cpp b/other/path_max_probability.cpp new file mode 100644 index 0000000..467829e --- /dev/null +++ b/other/path_max_probability.cpp @@ -0,0 +1,52 @@ +// 1514. Path with Maximum Probability +#include "leetcode.h" + +/* + * given an undirected weighted graph of 'n' nodes (0-indexed). represented by + * an edge list where 'edges[i] = [a, b]' is an undirected edge connecting the + * nodes 'a' and 'b' with a probability of success of traversing that edge + * 'succ_prob[i]'. given two nodes 'start, end', find the path with the maximum + * probability of success to go from 'start' to 'end' and return its success + * probability. if there is no path from 'start' to 'end', return 0. your answer + * will be accepted if it differs from the correct answer by at most '1e-5' + */ + +class Solution { +public: + double maxProbability(int n, vvd & edges, vector &succ_prob, + int start, int end) { + vector>> vvp(n); + for (int i = 0; i < edges.size(); i++) { + vvp[edges[i][0]].push_back({edges[i][1], succ_prob[i]}); + vvp[edges[i][1]].push_back({edges[i][0], succ_prob[i]}); + } + vector seen(n, 0); + priority_queue> pqp; + pqp.push({(double)1.0, start}); + vector mx(n, (double)0.0); + mx[start] = 1.0; + while (!pqp.empty()) { + auto top = pqp.top(); + pqp.pop(); + double prob_a = top.first; + int node = top.second; + if (!seen[node]) { + seen[node]++; + for (auto to : vvp[node]) + if (mx[to.first] < to.second * prob_a) { + mx[to.first] = to.second * prob_a; + pqp.push({mx[to.first], to.first}); + } + } + } + return mx[end]; + } +}; + +int main() { + Solution obj; + vvd e1 = {{0, 1}, {1, 2}, {0, 2}}, e2 = {{0, 1}, {1, 2}, {0, 2}}; + vector sp1 = {0.5, 0.5, 0.2}, sp2 = {0.5, 0.5, 0.3}; + printf("%f\n", obj.maxProbability(3, e1, sp1, 0, 2)); // expect: 0.25000 + printf("%f\n", obj.maxProbability(3, e2, sp2, 0, 2)); // expect: 0.30000 +} -- cgit v1.2.3