For this problem
#include <bits/stdc++.h>
#define letsgo int T; cin>>T;while(T--)
#define nl "\n"
using namespace std;
int32_t main() {
// your code goes here
letsgo{
long long N, M;
cin >> N >> M;
if(N<4 || M<4 || N+M<11) {
cout << -1 << nl;
continue;}
long long A[N];
for(long long i=0;i<N; i++){
cin >> A[i];
}
long long B[M];
for(long long i=0;i<M; i++)
{
cin >> B[i];
}
sort(A, A+N, greater<long long>());
sort(B, B+M, greater<long long>());
long long summ=0;
for(long long i=0; i<4; i++) summ+=A[i]+B[i];
long long count=0;
long long ap=4, bp=4;
while(count <3 && ap<N && bp<M){
if(A[ap]>B[bp]){
summ+=A[ap++];
}
else{
summ+=B[bp++];
}
count+=1;
}
while(ap<N && count<3){
summ+=A[ap++];
count +=1;
}
while(bp<M && count<3){
summ+=B[bp++];
count +=1;
}
cout << summ << nl;
}
}
My approach:
- check M and N can make valid array
- Sort in descending
- Add first 4 of each sorted array to get top 4 bowlers and batters
- set ap=4, bp=4 and use 2 finger method to get next 3 biggest cricketing skill plaers.
I ave this code, now i am honestly confident that the logic is right but for some case in the 3rd testfile it is saying runtime error and i am fairly new to cpp and not sure what is causing it. I have checked for array out of bound errors or the sort and i am sure all the indexes are being checked before being used and also manually wrote long long and took input everywhere. Please if someone could help me out, i know it is possible to do this by concatenng and then sorting and all but i just wanna know why is there a runtime error as it might help me in future.