-
Notifications
You must be signed in to change notification settings - Fork 11
/
SPOJ22329.cc
60 lines (54 loc) · 1.35 KB
/
SPOJ22329.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// SPOJ 22329: Chicks
// http://www.spoj.com/problems/CHICKEGG/
//
// Solution: binary search
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
using namespace std;
#define fst first
#define snd second
#define all(c) ((c).begin()), ((c).end())
double quad_eqn(double a, double b, double c) { // assuming a != 0
double D = b*b - 4*a*c, x1, x2;
if (b > 0) x1 = (-b - sqrt(D))/(2*a);
else x1 = (-b + sqrt(D))/(2*a);
x2 = c / (a * x1);
return max(x1, x2);
}
typedef long long ll;
// number of eggs in x days for the hens with ability d
ll egg(ll d, ll x) {
ll k = quad_eqn(1, 2*d-1, -2*x);
while (k*k + (2*d-1)*k <= 2*x) ++k;
while (k*k + (2*d-1)*k > 2*x) --k;
return k;
}
ll eggs(vector<ll> &ds, ll x) {
ll ans = 0;
for (auto d: ds) ans += egg(d, x);
return ans;
}
int main() {
int ncase; scanf("%d", &ncase);
for (int icase = 0; icase < ncase; ++icase) {
ll n, k; scanf("%lld %lld", &n, &k);
vector<ll> ds(n);
for (int i = 0; i < n; ++i)
scanf("%lld", &ds[i]);
ll lo = 0, hi = 1; // x <= lo ==> eggs < k; x >= hi ==> eggs >= k
while (eggs(ds, hi) < k) {
lo = hi;
hi *= 2;
}
while (lo+1 < hi) {
ll mi = (lo + hi) / 2;
if (eggs(ds, mi) < k) lo = mi;
else hi = mi;
}
printf("%lld\n", hi);
}
}