Explanation
The first step is to calculate the length and probability of each possible path. We can do this using DFS. We start of with a probability of 1, or 100%. Then, for each node, we divide the current path's probability by the number of possible next moves.
For example, if node 1 is connected to nodes 2 and 3, the probability of reaching node 2 is , or , and the probability of reaching node 3 is also . If node 3 is connected to nodes 4 and 5, the probability of reaching node 4 is and the probability of reaching node 5 is also . Let's say that nodes 2, 4, and 5 are leaf nodes. The possible paths are listed below:
- :
- :
- :
To calculate the expected length of the journey, we multiply each of the probabilities with the corresponding path length. In the example above, the expected length would be
In the code, for each node, we calculate the number of possible next moves by looping through the node's neighbors and counting how many are unvisited. If there are no such nodes, then the path has ended and we can add the length of the path times the probability to the final answer. Otherwise, we divide the probability (as described above) and continue the DFS.
Note: setprecision(10) sets the number of decimal places to be printed to be 10. See this for more details.
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;int n;vector<vector<int>> adj; // adjacency listvector<bool> visited; // stores which nodes have been visiteddouble ans;void dfs(int node, int current_length, double current_probability) {
Java
import java.util.*;public class Journey {public static double ans = 0;public static Map<Integer, List<Integer>> adjList; // adjacency listpublic static boolean[] visited; // stores which nodes have been visitedpublic static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();
Python
class Point:"""Represents a point or node along our depth-first traversal frontier."""def __init__(self, node: int, length: int, probability: float):self.node = nodeself.length = lengthself.probability = probabilityn = int(input())
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!