Official

D - Journey Editorial by en_translator


We have the following important fact.

Given is a trial that succeeds in probability \(p(p \neq 0)\). Then the expected number of trials until the first success (including the last succeeding one) is \(\frac{1}{p}\).

Proof:
Let \(X\) be the desired expected value. After a trial, we can terminate the trials if it is successful, while we go back to the starting point if unsuccessful; therefore we have equation \(X = 1 + (1 - p) X\).
By transformation we have \(pX = 1\), thus \(X = \frac{1}{p}\).

In this problem, we denote “the set of vertex in the connected component which Takahashi belongs” by \(S\). Also, we denote the number of elements by \(|S|\).
\(|S|\) increases by \(1\) if and only if a vertex that is not in \(S\) was chosen.
The expected number of operations until a vertex that is not contained in \(S\) is chosen for the first time is \(\frac{1}{\frac{N - |S|}{N}} = \frac{N}{N - |S|}\) due to the fact above. Since we start from \(|S| = 1\) and end when \(|S| = N\), so the answer is \(\frac{N}{N - 1} + \frac{N}{N - 2} + \frac{N}{N - 3} + \dots + \frac{N}{1}\).

This can be calculated in a total of \(O(N)\) time, so the problem has been solved.
The answer is at most \(1.2 \times 10^6\), so the precision does not matter if we use at least double-precision floating point numbers (double type).

posted:
last update: