Good job! Now that Heidi is able to distinguish between Poisson and uniform distributions, she is in a good position to actually estimate the populations.

Can you help Heidi estimate each village's population?


-----Input-----

Same as the easy version.


-----Output-----

Output one line per village, in the same order as provided in the input, containing your (integer) population estimate.

Your answer is considered correct if it is an integer that falls into the interval $[ \lfloor 0.95 \cdot P \rfloor, \lceil 1.05 \cdot P \rceil ]$, where P is the real population of the village, used to create the distribution (either Poisson or uniform) from which the marmots drew their answers.

Source: codeforces | Difficulty: HARD
Tags: Mathematics


Solutions:
def sampleVariance(V):
	X = sum(V) / len(V)
	S = 0.0
	for x in V:
		S += (X - x) ** 2
	S /= len(V) - 1
	return (X, S)
for i in range(int(input())):
	V = list(map(int, input().split()))
	(X, S) = sampleVariance(V)
	v1 = X
	v2 = (2 * X) ** 2 / 12
	if abs(v1 - S) < abs(v2 - S):
		print(int(X))
	else:
		print(max(V) + min(V) // 2)


from statistics import mean
from math import factorial, log, ceil
_lf = []

def logfact(n):
	nonlocal _lf
	CALCLEN = 2200
	if not _lf:
		_lf = [0] * CALCLEN
		for i in range(2, CALCLEN):
			_lf[i] = _lf[i - 1] + log(i)
	return _lf[n]

def unif_ml(xs):
	p2 = max(xs) / 2
	pmle = p2
	loglh = len(xs) * log(2 * pmle + 1)
	return (loglh, pmle)

def poiss_ml(xs):
	pml = mean(xs)
	loglh = len(xs) * pml + sum([-x * log(pml) + logfact(x) for x in xs])
	return (loglh, pml)

def solve(xs):
	(ul, Pu) = unif_ml(xs)
	(pl, Pp) = poiss_ml(xs)
	if ul < pl:
		p = 1.01 * Pu
	else:
		p = Pp
	print(ceil(p))

def __starting_point():
	v = int(input())
	for i in range(v):
		xs = [int(x) for x in input().split()]
		solve(xs)
__starting_point()


v = int(input())
eps = 170

def ans(a):
	a.sort()
	if len(a) % 2 == 0:
		med = a[len(a) // 2]
	else:
		med = (a[len(a) // 2] + a[len(a) // 2 - 1]) // 2
	l = med - med // 2
	r = med + med // 2
	c1 = c2 = 0
	for i in a:
		if i >= l and i <= r:
			c1 += 1
		else:
			c2 += 1
	if abs(c1 - c2) <= eps:
		return (med, 'uniform')
	else:
		return (med, 'poisson')
for i in range(v):
	cur = [int(i) for i in input().split()]
	b = ans(cur)
	if b[1] == 'poisson':
		print(b[0])
	else:
		print((max(cur) - min(cur)) // 2)