|
| 1 | +from collections import defaultdict, deque |
| 2 | +from typing import List |
| 3 | + |
| 4 | + |
| 5 | +class Solution: |
| 6 | + def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float: |
| 7 | + graph = defaultdict(list) |
| 8 | + for i, (a, b) in enumerate(edges): |
| 9 | + graph[a].append([b, succProb[i]]) |
| 10 | + graph[b].append([a, succProb[i]]) |
| 11 | + |
| 12 | + max_prob = [0.0] * n |
| 13 | + max_prob[start] = 1.0 |
| 14 | + |
| 15 | + queue = deque([start]) |
| 16 | + while queue: |
| 17 | + cur_node = queue.popleft() |
| 18 | + for nxt_node, path_prob in graph[cur_node]: |
| 19 | + |
| 20 | + # Only update max_prob[nxt_node] if the current path increases |
| 21 | + # the probability of reaching nxt_node. |
| 22 | + if max_prob[cur_node] * path_prob > max_prob[nxt_node]: |
| 23 | + max_prob[nxt_node] = max_prob[cur_node] * path_prob |
| 24 | + queue.append(nxt_node) |
| 25 | + |
| 26 | + return max_prob[end] |
| 27 | + |
| 28 | + |
| 29 | +# Take input from the user |
| 30 | +n = int(input("Enter the number of vertices (n): ")) |
| 31 | +m = int(input("Enter the number of edges (m): ")) |
| 32 | +edges = [] |
| 33 | +succProb = [] |
| 34 | + |
| 35 | +for i in range(m): |
| 36 | + print(f"Enter the source and destination vertices of edge {i+1}:") |
| 37 | + u = int(input()) |
| 38 | + v = int(input()) |
| 39 | + edges.append([u, v]) |
| 40 | + |
| 41 | +for i in range(m): |
| 42 | + print(f"Enter the success probability of edge {i+1}: ") |
| 43 | + p = float(input()) |
| 44 | + succProb.append(p) |
| 45 | + |
| 46 | +start = int(input("Enter the start vertex: ")) |
| 47 | +end = int(input("Enter the end vertex: ")) |
| 48 | + |
| 49 | +# Create an instance of Solution |
| 50 | +solution = Solution() |
| 51 | + |
| 52 | +# Calculate maximum probability |
| 53 | +maxProbability = solution.maxProbability(n, edges, succProb, start, end) |
| 54 | + |
| 55 | +# Output the result |
| 56 | +print(f"The maximum probability from vertex {start} to vertex {end} is: {maxProbability}") |
0 commit comments