Problem: 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 <image>, 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.

Solution (in CPP):

Solution:
#include <bits/stdc++.h>
using namespace std;
const double e = exp(1);
const int N = 250;
const int P = 2000;
double fac[P + 1] = {0};
int main() {
  for (int i = 1; i <= P; i++) fac[i] = fac[i - 1] + log(i);
  int n;
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    double m = 0;
    int l = P + 1, r = -1;
    int a[N] = {0};
    for (int j = 0; j < N; j++) {
      scanf("%d", &a[j]);
      m += a[j];
      l = min(l, a[j]);
      r = max(r, a[j]);
    }
    m /= N;
    double p = N * log(2 * m + 1);
    for (int j = 0; j < N; j++) p += -m + a[j] * log(m) - fac[a[j]];
    double ansv = -1e300;
    int ansp = 10;
    if (p > 0) {
      for (int j = 10; j <= 1000; j++) {
        double p = -j * N;
        for (int k = 0; k < N; k++) p += a[k] * log(j);
        if (p > ansv) {
          ansp = j;
          ansv = p;
        }
      }
    } else {
      ansp = max(min((r + 1) / 2, 1000), 10);
    }
    printf("%d\n", ansp);
  }
  return 0;
}