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 int MAX = 7000;
double log_fact[MAX];
double PoissonProb(int p, int k) {
  (k) = min((k), (MAX - 1));
  return k * log(p) - p - log_fact[k];
}
int main() {
  log_fact[0] = 0;
  for (int i = 1; i < MAX; ++i) log_fact[i] = log_fact[i - 1] + log(i);
  int q;
  scanf("%d", &q);
  for (int i = 0; i < q; ++i) {
    vector<int> in(250);
    double sum = 0.0;
    for (int& e : in) scanf("%d", &e), sum += e;
    int p = ceil(sum / ((int)(in).size()));
    double eq_prob = ((int)(in).size()) * -log(2 * p + 1);
    double poisson_prob = 0;
    for (int& e : in) poisson_prob += PoissonProb(p, e);
    if (poisson_prob > eq_prob)
      printf("%d\n", p);
    else {
      int mid = (*max_element(in.begin(), in.end()) +
                 *min_element(in.begin(), in.end())) /
                2;
      (mid) = max((mid), (10));
      (mid) = min((mid), (1000));
      printf("%d\n", mid);
    }
  }
  return 0;
}