fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. typedef long long int ll;
  5.  
  6. void solve() {
  7. ll n, c;
  8. cin >> n >> c;
  9.  
  10. // Use vector instead of VLA to prevent stack overflow
  11. vector<ll> b(n + 1, 0);
  12. ll sum = 0;
  13.  
  14. for (ll i = 1; i <= n; i++) {
  15. cin >> b[i];
  16. sum += b[i];
  17. }
  18.  
  19. // Sort from index 2 to n
  20. sort(b.begin() + 2, b.end());
  21.  
  22. ll answer = 0;
  23.  
  24. // Precompute prefix sums for the sorted region to achieve O(1) range queries
  25. vector<ll> pref(n + 1, 0);
  26. for (ll i = 2; i <= n; i++) {
  27. pref[i] = pref[i - 1] + b[i];
  28. }
  29.  
  30. // Single loop: O(N) instead of O(N^2)
  31. for (ll do_it = 1; do_it <= n - 1; do_it++) {
  32. // 1. Sum of the smallest 'do_it' elements starting from index 2
  33. ll sum_low = pref[1 + do_it];
  34. ll u1 = (sum - sum_low) * sum_low;
  35.  
  36. // 2. Sum of the largest 'do_it' elements ending at index n
  37. ll sum_high = pref[n] - pref[n - do_it];
  38. u1 = min(u1, (sum - sum_high) * sum_high);
  39.  
  40. if (u1 <= c) {
  41. answer = do_it;
  42. }
  43. }
  44.  
  45. cout << n - answer << "\n";
  46. }
  47.  
  48. int main() {
  49. // Fast I/O optimization
  50. ios_base::sync_with_stdio(false);
  51. cin.tie(NULL);
  52.  
  53. ll t;
  54. cin >> t;
  55. while (t--) {
  56. solve();
  57. }
  58. return 0;
  59. }
Success #stdin #stdout 0s 5320KB
stdin
4
3 1000000000000000000
2000000 4000000 5000000
4 150
100 1 1 1
6 1275
35 15 10 25 10 5
6 400
35 15 10 25 10 5
stdout
1
3
4
6