Author | Hasan Saleh |
Prepared by | Hasan Saleh |
Edited by | Hasan Saleh |
Let S=\sum_i a_i and let b_1 \ge b_2 be the two largest values , with b_2=0 when n<3 . The answer is
All three bounds are necessary . Fix a number of collections . They consume balls , so 3k \le S . A single collection touches a box at most once , so across collections the fullest box gives away at most balls and the remaining boxes must supply 2k \le S-b_1 . For the same reason the two fullest boxes together give at most , and the rest must supply k \le S-b_1-b_2 .
They are also sufficient , and the clean certificate is the capacity condition : box can give at most \min(a_i,k) balls , and collections are achievable iff \sum_i \min(a_i,k) \ge 3k , since capping each box at and repeatedly serving the three largest remaining capacities never forces a box into the same collection twice . Let j=\#\{i : a_i>k\} for the above , so \sum_i \min(a_i,k)=jk+\sigma where is the total of the boxes with a_i \le k . If j=0 the sum is S \ge 3k . If j=1 it is k+(S-b_1) \ge k+2k . If j=2 it is 2k+(S-b_1-b_2) \ge 3k . If j \ge 3 it is at least outright . So the condition holds in every case .
This is the exact analogue of \min(\lfloor S/2 \rfloor , S-b_1) for the two-box version ; carrying that formula over unchanged as \min(\lfloor S/3 \rfloor , S-b_1) is wrong , on a=[5,5,1] it reports while the answer is , because there two boxes bind jointly rather than one alone . Note also that reaches 2 \cdot 10^{14} , so the whole computation must be done in -bit arithmetic .
#include<bits/stdc++.h>
using namespace std;
#define int long long
void solve(){
int n;
cin>>n;
int s=0,b1=0,b2=0;
for(int i=0;i<n;i++){
int x;
cin>>x;
s+=x;
if(x>b1){
b2=b1;
b1=x;
}
else if(x>b2){
b2=x;
}
}
cout<<min(s/3,min((s-b1)/2,s-b1-b2))<<"\n";
}
signed main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
cin>>t;
while(t--){
solve();
}
}Complexity : per test case , no sorting needed .