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 {
      printf("%d\n", (*max_element(in.begin(), in.end()) + 1) / 2);
    }
  }
  return 0;
}