There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads.
Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities.
Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link https://en.wikipedia.org/wiki/Expected_value.
Input
The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities.
Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road.
It is guaranteed that one can reach any city from any other by the roads.
Output
Print a number — the expected length of their journey. The journey starts in the city 1.
Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.
Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .
Examples
Input
4
1 2
1 3
2 4
Output
1.500000000000000
Input
5
1 2
1 3
3 4
2 5
Output
2.000000000000000
Note
In the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5.
In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to compute expected total length traveled by a random walk that starts at node 1, and at each visited node (including start) the horse moves uniformly at random to a neighbor that has not been visited before (i.e., it traverses edges of a random simple path from root into the tree, without backtracking, essentially a random depth-first exploration? Actually it's a random self-avoiding walk on a tree: it starts at root, and at each step moves to an unvisited neighbor uniformly. Since it's a tree, there is no cycle; once you leave a node, you cannot go back because the only neighbor you could return to is the parent, but that parent is visited already (since you came from there). So the walk proceeds into a branch until it reaches a leaf (or a node where all neighbors are visited). Since it's a tree, the walk is essentially a random simple path starting from root, where at each step you choose uniformly among the unvisited neighbors. But note: In a tree, the set of unvisited neighbors at a node consists of all its children (i.e., those not visited) because the parent is already visited (except at root which has no parent). So from any node, the walk moves to one of its children (neighbors not visited) uniformly. It stops when the node is a leaf (no children) or all children have been visited? Actually since it only moves to unvisited neighbors, when at a node all neighbors are visited (including parent), there is no place to go, so stops. Since we never revisit nodes, the path is simple and will eventually stop at some node. So it's a random simple path from root to some node; the process chooses which child to go into at each branching, uniformly among the children. The journey ends when it reaches a leaf? But consider internal node with children: if it has children, there will be at least one unvisited neighbor (unless all children visited, but we never visited any child because we never backtrack, so from root we only go forward; we never explore multiple branches because we don't return. So we only go down a single path until we hit a leaf: because at each node we pick a child uniformly among its children. The walk never goes back, so we only traverse a single branch from root to some leaf. Indeed, it's like a random leaf? But what if the tree is not rooted? The root is node 1. So we consider node 1 as root; its neighbors are its children. At node 1, we pick a child uniformly and go there. That child has its own neighbors: one is its parent (node 1) which is visited, so remaining are its children. So again, we pick a child uniformly among its children, etc. So the walk continues until we hit a node that has no children (i.e., a leaf in the rooted tree). So the journey length is the distance from root to the leaf that we end at. So the expected distance from root to a leaf that is reached by a random process of choosing uniformly among children at each step. However, not all leaves are equally likely: the probability of reaching a leaf depends on the branching probabilities along the path.
Thus we need expected length of path from root to a leaf, where from each node, the next step is chosen uniformly among its children (if any). If node has no children, we stop (the leaf itself is the current node). The length is the number of edges traversed (the distance from root to the final node). For root, if it has no children (n=1), journey length is 0? But note: Journey starts at city 1 and they are at city 1 initially. The horse stops when there are no unvisited cities to go to. If n=1, there are no roads, so they start at city 1 and there are no moves, so length 0. Expected length = 0. So handle n=1.
For n>1, we need to compute expected distance from root to leaf under this random child selection.
This is reminiscent of expected length of a random path from root to a leaf in a tree where at each node you pick a child uniformly. That's essentially the expected depth of a random leaf, but not uniform over leaves. Could compute recursively.
Let f(u) be the expected remaining distance from node u to the leaf reached by this process, i.e., the expected number of edges to be traversed from u (including any steps from u) until stop. Actually if u is the current node, and the walk is at u, what is the expected total length from u onward (including edges we will travel). At node u, if it has no children (i.e., degree=1 and not root? Actually careful: In rooted tree at root, if root has no children (n=1) it's leaf. For node u in general (non-root), its children are neighbors except parent. So the condition "no unvisited neighbors" occurs when degree(u) = 1 for non-root (since parent is visited) OR if root and degree 0. So we can treat leaf as node with no children (i.e., degree = 1 except root?). But better to define children as neighbors excluding parent. So let children(u) be set of neighbors except parent (for root, all neighbors). Then the process: from u, if children(u) is empty, we stop (so remaining length = 0). Otherwise, we choose uniformly a child v among children(u), traverse edge (u,v) (length 1), then from v we continue with expected remaining length f(v). So f(u) = 0 if children empty; else f(u) = (1/|children|) * sum_{v in children(u)} (1 + f(v)). That is:
f(u) = 1 + (1/deg) * sum_{v} f(v), where deg = number of children.
But note that f(v) is the expected remaining length from v onward, inclusive of edges from v. So we can compute f(1) as the expected total length from root.
Thus we need to compute f(1) for the tree with root at 1. The tree is given undirected; we can root it at 1 and compute children via BFS/DFS.
However, is this correct? Let's test with examples.
Example 1:
n=4, edges: 1-2,1-3,2-4.
Root=1. Children of 1: 2,3. Child 2: its children: neighbor 4 (since parent 1 excluded) -> children(2) = {4}. Child 3: leaf (no children). Child 4: leaf (no children) (since parent 2).
Compute f(3)=0 (leaf). f(4)=0.
f(2) = if children nonempty: children= {4}, deg=1 -> f(2) = 1 + f(4)=1.
f(1) = children= {2,3}, deg=2 -> f(1) = 1 + (f(2)+f(3))/2 = 1 + (1+0)/2 = 1.5. Matches output.
Example 2:
n=5, edges:1-2,1-3,3-4,2-5.
Root=1. Children: 2,3.
Node2: neighbors: 1 (parent),5 -> children={5}. Node5: leaf (no children). So f(5)=0. f(2)=1+f(5)=1.
Node3: neighbors:1(parent),4 -> children={4}. Node4: leaf (no children). f(4)=0. f(3)=1.
f(1)=1+(f(2)+f(3))/2=1+(1+1)/2=2. Output 2. Matches.
So indeed it's simply computing this recursive expectation.
But is there any nuance? The horse may stop also at nodes that are not leaves? The process stops when there are no unvisited neighbors. In a tree, if we go from root, we only ever visit a single path; we never go to siblings. At a node that is not a leaf (has children), there is at least one unvisited neighbor (its children), so it won't stop. So indeed it only stops at leaves. So the recursion works.
Thus we need to compute for each node, the expected remaining steps to leaf, given uniform choice among its children. But careful: The recursion above uses children excluding parent. For root, all neighbors are children. For other nodes, we need to know the parent to determine children set.
We can compute f(u) via DFS from root. The recursion is f(u) = 0 if no children; else = 1 + (1/|children|) * sum_{v} f(v). Since f(v) depends on descendants, we can compute in postorder.
Complexity: O(n). n up to 100k, fine.
But we should double-check that the process indeed never revisits nodes and the tree property ensures that we cannot go back to parent because it's visited. That's correct.
Thus answer is f(1). Edge case n=1: children(1)=0, f(1)=0.
Now, is there any nuance about the horse starting at city 1 and being "on a horse", and the journey length includes the distance traveled from the starting point? The definition: "The journey starts in the city 1. What is the expected length (expected value of length) of their journey?" They travel along roads; each road length 1. So total length is number of edges traversed. In our recursion, f(1) is expected number of edges traveled from city 1 onward. Starting at city 1, they haven't traveled any edge yet. When they move from 1 to child, they travel 1 edge. So our f(1) accounts for that. So it's correct.
But wait: The horse, when reaching a city, goes to one of the cities connected to the current city that they haven't been before. At the start, they are at city 1. The horse goes to a neighbor not visited. So they will definitely leave city 1 if there is at least one neighbor (n>1). So in our recursion, f(1) for root with children >0 includes that first step. That's fine.
Now the recursion yields answer. So we can implement.
But is there any catch? Could there be a scenario where the horse might have multiple unvisited neighbors and some of them are not necessarily children? Because consider node visited: Suppose we are at node u, we came from parent p. All visited nodes are ancestors (the path from root to u). The unvisited neighbors are all neighbors except p and any visited (but the only visited neighbors is p, since tree has no cycles; all other neighbors are children (unvisited)). So it's exactly as we used.
Thus solution: root the tree at 1, compute children, then compute f via DFS.
But we need to compute with double precision, careful for large depth? Not an issue.
Now I want to confirm that this recursion indeed gives the expected path length. It's like the expected distance to a leaf when moving uniformly among children. That is a standard result.
Thus the answer is straightforward.
But is there any hidden twist? Possibly the horse may not stop at a leaf? Suppose the horse reaches a node where there are multiple unvisited neighbors, but if it chooses one, later it could come back? No, because it cannot go back because the parent is visited; there is no mechanism to revisit. So it's a simple random walk along a single branch.
Thus the problem reduces to this.
However, I recall there is known Codeforces problem "Theon and Yara Greyjoy" or something? Actually I think this problem is from Codeforces Round? Let's search memory: There is problem "Journey" from Codeforces? Actually there is CF 839C "Journey" which is about expected length of a random walk until leaf, with uniform probability among children. Yes! I recall: CF 839C - Journey. The problem description is exactly: "There are n cities and n-1 roads... Theon and Yara are on a horse..." That is the problem. And the solution is to compute expected length as we described.
Yes, it's exactly CF 839C. The editorial says to compute sum over all leaf probabilities times distance. Alternatively DFS with probability.
But careful: In some versions, the horse chooses uniformly among all unvisited neighbors (including parent if not visited)? But parent is visited, so not included. So it's the same.
Thus we are good.
Now let's think about potential pitfalls: The recursion f(u) = 1 + average of f(v) works only if we include the step to child. But we must ensure that we don't add 1 when there are no children. For leaf, f=0. That matches.
Thus solution is simple.
However, note: For root, if it has exactly one child, f(1) = 1 + f(child). That's fine.
But what about nodes with children that are not leaves? Recursion holds.
One subtle nuance: The horse might stop at a node that is not a leaf if all its neighbors are visited, but that only happens if it's a leaf or after exploring multiple branches? But we only go down one path; we never explore multiple branches, so we never have visited children. So it's leaf.
Thus answer.
Now about implementation: We'll create adjacency list. Then run DFS from root 1, parent = -1. For each node, compute list of children as neighbors excluding parent. If no children, return 0. Else, compute sum of dfs(child) for children, then f = 1.0 + sum / count. Return that.
Note: The tree can be up to 100k nodes, recursion depth may exceed default recursion limit in Python (1000). So we need to either increase recursion limit or implement iterative DFS. We'll use sys.setrecursionlimit(200000) and hope it's okay, but Python recursion may still be slow for deep tree if it's a line of 100k nodes, depth 100k, recursion might cause stack overflow? Actually Python recursion limit can be set high, but each recursion uses stack and may cause memory issues or recursion depth limit, but we can set to 200000, but still there is risk of hitting C stack limit? In CP, typical Python solutions set recursionlimit to something like 300000 and it's fine for 100k depth? I think Python recursion can handle about 10^5 with increased limit, but some platforms may have segmentation fault due to C stack. Safer to use iterative DFS (stack) to avoid recursion. But many CP solutions for this problem use recursion with recursionlimit and it passes. We'll implement iterative to be safe.
We'll do an iterative post-order DFS. We can do two-pass: first a stack for traversal, record parent and order, then process nodes in reverse order.
Procedure:
Build adjacency list.
Use stack for DFS to get parent array and order list.
Initialize stack = [(1, -1)] while stack: pop (node, parent), record parent[node]=parent, push children (neighbors except parent) onto stack? But we need post-order, so we can push (node, parent) and then iterate children, but ensure we process after children. Another approach: use stack to do a preorder traversal and record order of visitation, then process nodes in reverse order, because for any node, its children appear later in the order (if we do a DFS). So we can do iterative DFS to record parent and traversal order.
Pseudo:
parent = [0]*(n+1)
order = []
stack = [1]
parent[1] = -1
while stack:
u = stack.pop()
order.append(u)
for v in adj[u]:
if v != parent[u]:
parent[v] = u
stack.append(v)
But careful: This pushes children; since stack is LIFO, the order of processing is not exactly DFS but still each child will be processed after pushing, but the order list will have node before its children? Actually here we pop u, then we push all children. So the node u is appended before its children are processed; children will be popped later. So order list has parent before children (preorder). When we later process in reverse order, children will be processed before parent because reverse order of preorder ensures that children are after parent in the list, so in reverse they come before parent. However, note that because we push all children, they will be processed in some order. But does it guarantee that all descendants appear after u? Yes, because we only push children when we pop u, and then later we will pop children, but before popping children we might pop other nodes from stack? Since we push all children, and stack is LIFO, the order of children is reversed relative to adjacency, but that's okay. The crucial property: For any edge u->v (where v is child), u is discovered (popped) before v? Actually with this method: we push root. Then pop root, append root, then push its children. After pushing children, the next pop will be one of the children (the last pushed). That child will then push its children, and so on. So indeed, when we pop a node, its parent has already been popped and appended earlier. So in order list, parent appears before child. So reverse order will process children before parents. Good.
Thus we can compute expected values in reverse order.
We need children list for each node. We can compute children after we have parent: For each node, children = neighbors except parent. So we can compute children count and also maybe store list; but we need sum of f values of children when processing a node. So when processing in reverse order, for each node we have its children already processed (since children appear later in order, and we are going reverse, so children already have computed f). So we can compute f[u] as: if node has no children (i.e., degree - (1 if parent != -1 else 0) == 0): f[u]=0. Else: f[u] = 1 + (sum_{child} f[child]) / num_children.
We need to store f as double array.
We also need to know the children of each node. Since we have parent, we can compute children on the fly: while processing node u, we can iterate over adj[u], if v != parent[u] then v is child. That's okay. For each node we will iterate over its neighbors once. Overall O(n) as each edge visited twice (once for each endpoint during processing). That's fine.
But careful: In reverse order processing, when we process node u, we need to know its children's f values. Since we processed children already, they are in f array. So we can compute sum.
while stack:
u = stack.pop()
order.append(u)
for v in adj[u]:
if v != parent[u]:
parent[v] = u
stack.append(v)
Note: For root, parent[1] = -1, we must ensure that when checking v != parent[u], parent[u] might be -1, which is not in range, but v are >=1, so it's fine.
Initialize f = [0.0]*(n+1)
Process nodes in reverse order (from last in order to first):
for u in reversed(order):
count = 0
total = 0.0
for v in adj[u]:
if v != parent[u]: # child
count += 1
total += f[v]
if count > 0:
f[u] = 1.0 + total / count
else:
f[u] = 0.0
Print f[1] with appropriate precision: e.g., print("{:.15f}".format(f[1])) or just print(f[1]) with default formatting? Better to use print with high precision. Typically Python's print with repr might be enough? But to be safe, format to 15 decimal places.
But be careful: In the reverse order, does root appear first in order? With the above stack method, we push root, pop it, append it, then push children. So order list starts with root. Then later children appear. So reversed order starts with leaf nodes and ends with root. Good.
Now complexity: O(n). Memory: O(n). Works.
But we must ensure that the tree is rooted correctly. For nodes with parent=-1, condition v != parent[u] works because parent[u]==-1 and v >=1, so true.
Edge case: n=1: adjacency list empty. order = [1] after DFS? We have stack [1], pop, append, then loop over adj[1] (empty). So order = [1]. Then processing reversed: count = 0, f[1]=0. So we could handle n=1 in same code; but our earlier step to print 0.0 is fine, but we could skip and it will output 0.0. However, careful: The journey length when n=1 is 0; yes. So we can just run general code, it will produce f[1]=0. So no need special case.
But test: n=1, no roads. According to problem: n-1 roads, so with n=1 there are 0 roads. Journey starts at city 1, no moves, length 0. So answer 0. That's fine.
Now, we must ensure that the answer is expected length, not expected number of steps? Actually length = sum of road lengths, each is 1, so it's the number of edges traversed. So it's steps count.
Thus solution is ready.
But wait: In some versions of this problem (CF 839C), the horse moves to any unvisited neighbor uniformly, but the horse might also stop at a node that is not a leaf if it has visited all neighbors? That's leaf. So it's the same.
Thus answer is f(1).
Now I will think if there's any nuance about the horse possibly not moving if there are no unvisited neighbors at start? At start, if n=1, yes, no moves. So covered.
Now confirm with other possible trees. For a chain of length n (like 1-2-3-...-n). Root=1, children: 2 only? Actually 1 connected to 2, so children(1)={2}. Node2: parent=1, child={3}. ... Node(n-1): child={n}. Node n: leaf. So f(n)=0, f(n-1)=1+0=1, f(n-2)=1+ f(n-1)=2,... f(1)=n-1. So expected length = n-1 (deterministic because at each node only one child). So answer is n-1. That seems plausible: they will go straight to the end of chain. So for n=2, answer 1.
Now consider a star: root 1 connected to many leaves. children(1) = leaves (k). f(leaf)=0. So f(1) = 1 + (0)/k = 1. So expected length = 1. Because from root they will go to a leaf in one step (since all leaves directly connected). So answer 1. That's correct.
Now consider a tree where root has one child which is internal node with many leaves. Let's compute: root->A, A has m leaves. f(A) = 1 + 0 =1 (since each leaf gives 0, average 0). So f(1) = 1 + f(A) = 2. So expected length = 2. That matches: from root go to A (1 step), then from A choose a leaf uniformly (1 step) -> total 2.
So everything seems consistent.
Thus solution is straightforward.
But wait: Is there any nuance about the horse moving only to cities they weren't before, but could there be a scenario where the horse goes to a city that they have visited? No, they don't.
Thus problem solved.
Now we can produce final answer.
However, sometimes the problem might be misinterpreted: The horse chooses uniformly among all neighbors, not just unvisited? But the problem says: "it only goes to cities in which they weren't before." So only unvisited. So correct.
Now also there is possibility that the horse could stop at a node that has visited neighbors only? That is leaf.
Thus algorithm is correct.
Now we will produce the solution code.
Implementation details:
Use sys.stdin.read to read all input quickly.
Parse ints.
Build adjacency list as list of lists.
Pseudo-code:
import sys
def main():
data = sys.stdin.read().strip().split()
if not data: return
it = iter(data)
n = int(next(it))
adj = [[] for _ in range(n+1)]
for _ in range(n-1):
u = int(next(it)); v = int(next(it))
adj[u].append(v)
adj[v].append(u)
code
if n == 1:
print("0.0")
return
parent = [0]*(n+1)
order = []
stack = [1]
parent[1] = -1
while stack:
u = stack.pop()
order.append(u)
for v in adj[u]:
if v != parent[u]:
parent[v] = u
stack.append(v)
f = [0.0]*(n+1)
for u in reversed(order):
cnt = 0
total = 0.0
for v in adj[u]:
if v != parent[u]:
cnt += 1
total += f[v]
if cnt > 0:
f[u] = 1.0 + total / cnt
else:
f[u] = 0.0
# print with sufficient precision
print("{:.15f}".format(f[1]))
if name == "main":
main()
We can also use recursion but iterative is safe.
Now let's test quickly with given examples:
Example 1: n=4 edges as above. The code should output 1.5. Example 2: 2.0.
Thus final answer.
But wait: There might be floating point error accumulation; using double is fine.
Now discuss potential pitfalls: The order list produced by stack DFS might not guarantee that parent appears before all children? In a tree, if we push all children, then later we might push a child, then before processing that child we might process another branch? Actually using stack LIFO, we push all children of u onto stack. Then the top of stack is the last pushed child. We then pop it and process it, pushing its children, etc. So indeed we do a depth-first order but with reversed adjacency order. However, if we push all children, after processing a child, its children get pushed and processed before we pop the next child of u. So the order list will have u, then the first child (the last in adjacency) and all its descendants, then the next child of u, etc. So yes, u appears before all its descendants. So reversed order will have all descendants before u. So fine.
But what about the case where we have a node with children that we never processed because of stack order? No, we process all nodes.
Thus correct.
Alternative: We could also use BFS to get parent and then do recursion from leaves upward using a queue and indegree counting (like topological order on tree). But easier is DFS.
Now finalize.
Now, the problem statement says: "Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6." So formatting to 15 decimal places is safe.
Now produce final answer.
But I'd like to double-check whether the expectation is indeed as computed. Let's think of a more complex example: root 1 has two children A and B. A has two leaves A1 and A2. B is leaf. Then compute:
Now compute manually: From 1, choose child A with prob 0.5, then from A choose leaf: total length = 2 (1+1). From 1, choose child B with prob 0.5: total length = 1. So expected = 0.52 + 0.51 = 1.5. Good.
Now, what if A had one leaf: f(A)=1, B leaf f(B)=0. same.
Now, what if A had a child C which has leaves etc. So recursion holds.
Thus solution stands.
One more nuance: The horse stops when there are no unvisited cities to go to. In our process, at a node with children, we always move to a child. But consider node with children but that child leads to a dead end; still we move. So no problem.
Thus solved.
Now write final answer.
But I'm asked: "There are n cities and n - 1 roads in the Seven Kingdoms..." and it's about expected length. We'll produce solution.
Now incorporate in final message: code in python.
I'll also include comments for clarity.
Potential performance improvements: None needed.
Now output.
Thus final answer. ```python
import sys
def main():
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(data)
n = int(next(it))
adj = [[] for _ in range(n + 1)]
for _ in range(n - 1):
u = int(next(it))
v = int(next(it))
adj[u].append(v)
adj[v].append(u)
code
# iterative DFS to obtain parent array and traversal order
parent = [0] * (n + 1)
order = []
stack = [1]
parent[1] = -1 # root has no parent
while stack:
u = stack.pop()
order.append(u)
for v in adj[u]:
if v != parent[u]:
parent[v] = u
stack.append(v)
# dp[u] = expected remaining length from u
dp = [0.0] * (n + 1)
# process nodes in reverse order (children before parent)
for u in reversed(order):
cnt = 0
total = 0.0
for v in adj[u]:
if v != parent[u]: # v is a child
cnt += 1
total += dp[v]
if cnt > 0:
dp[u] = 1.0 + total / cnt
# else: dp[u] stays 0.0 (leaf)
# answer with sufficient precision
print("{:.15f}".format(dp[1]))