Skip to content

Commit 07689ed

Browse files
authored
Merge pull request #423 from Aaryan-Degama/main
d6q1
2 parents c978dfb + d17142e commit 07689ed

1 file changed

Lines changed: 86 additions & 0 deletions

File tree

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
// link : https://codeforces.com/contest/2014/submission/356025598
2+
3+
#include <bits/stdc++.h>
4+
using namespace std;
5+
6+
using ll = long long;
7+
8+
void solve() {
9+
int n;
10+
cin >> n;
11+
12+
vector<ll> a(n);
13+
ll sum = 0;
14+
for (int i = 0; i < n; i++) {
15+
cin >> a[i];
16+
sum += a[i];
17+
}
18+
19+
if (n <= 2) {
20+
cout << -1 << "\n";
21+
return;
22+
}
23+
24+
sort(a.begin(), a.end());
25+
26+
ll l = 0, r = 1e18, ans = -1;
27+
28+
while (l <= r) {
29+
ll mid = (l + r) / 2;
30+
31+
long double avg = (long double)(sum + mid) / n;
32+
long double half = avg / 2.0;
33+
34+
int cnt = 0;
35+
for (ll v : a) {
36+
if ((long double)v < half)
37+
cnt++;
38+
}
39+
40+
if (cnt > n / 2) {
41+
ans = mid;
42+
r = mid - 1;
43+
} else {
44+
l = mid + 1;
45+
}
46+
}
47+
48+
cout << ans << "\n";
49+
}
50+
51+
int main() {
52+
ios::sync_with_stdio(false);
53+
cin.tie(nullptr);
54+
55+
int t;
56+
cin >> t;
57+
while (t--) {
58+
solve();
59+
}
60+
61+
return 0;
62+
}
63+
64+
65+
/*
66+
Approach:
67+
We are allowed to add a non-negative value x to the total sum of the array.
68+
After adding x, let the new average be:
69+
avg = (sum + x) / n
70+
We want more than half of the elements to be strictly less than:
71+
avg / 2
72+
If n <= 2, this is impossible, so we directly output -1.
73+
74+
Since adding more x only increases avg, the condition becomes monotonic.
75+
Hence, we can binary search the minimum x.
76+
For a fixed x:
77+
* Compute avg and avg/2
78+
* Count how many elements are < avg/2
79+
* If count > n/2, the condition is satisfied.
80+
81+
Binary search over x in the range [0, 1e18] and keep the minimum valid x.
82+
83+
Time Complexity: O(n log n)
84+
85+
Space Complexity: O(n)
86+
*/

0 commit comments

Comments
 (0)