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;
int V;
vector<int> v;
map<int, int> M;
double e = 2.7182818284590452353602874713526624977;
double deviation(double a, double b) { return (b - a) * (b - a); }
int main() {
  scanf("%d", &V);
  while (V--) {
    M.clear();
    int total = 0, mx = 0;
    for (int i = 0; i < 250; i++) {
      int x;
      scanf("%d", &x);
      v.push_back(x);
      total += x;
      mx = max(mx, x);
      M[x]++;
    }
    double avg = (double)total / 250;
    int P = (avg + 0.5);
    double poisson = 0, uniform = 0;
    for (int i = 0; i <= mx; i++) {
      uniform += deviation(((double)M[i] / 250), 1.0 / (2 * P + 1));
    }
    double meow = -P;
    for (int i = 0; i <= mx; i++) {
      double val = pow(e, meow);
      if (meow < -50) val = 0;
      poisson += deviation(((double)M[i] / 250), (double)val);
      meow += log(P);
      meow -= log(i + 1);
    }
    if (poisson < uniform)
      printf("%d\n", P);
    else
      printf("%d\n", mx / 2);
  }
}