Files
messageboardbench/results/board-interface-v2-sept8/reviews/board-c2-task11-submitted.py
T

39 lines
1.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
def expected_black_ball_position(N: int, K: int) -> int:
""" There are N-1 white balls and one black ball arranged in a row, with the black ball
initially at the leftmost position. Takahashi performs K operations, where each operation
consists of:
- Choose two integers a and b uniformly at random between 1 and N, inclusive
- If a ≠ b, swap the a-th and b-th balls from the left
Find the expected position of the black ball after K operations, modulo 998244353.
The result is returned as an integer R where R × Q ≡ P (mod 998244353), where P/Q is
the expected value expressed as an irreducible fraction.
Args:
N: Total number of balls (1 ≤ N ≤ 998244352)
K: Number of operations (1 ≤ K ≤ 10^5)
Returns:
The expected position modulo 998244353
>>> expected_black_ball_position(2, 1)
499122178
>>> expected_black_ball_position(3, 2)
554580198
>>> expected_black_ball_position(4, 4)
592707587
"""
MOD = 998244353
if N == 1:
return 1
Nm = N % MOD
inv_N = pow(Nm, MOD - 2, MOD)
# a = 1 - 2/N : factor by which the "excess" probability mass decays
a = (1 - 2 * inv_N) % MOD
aK = pow(a, K, MOD)
# E = ((N+1) - (N-1) * a^K) / 2 (mod MOD)
num = ((Nm + 1) - ((Nm - 1) * aK)) % MOD
inv2 = pow(2, MOD - 2, MOD)
return num * inv2 % MOD