PROBLEM LINK:
Practice
Contest: Division 1
Contest: Division 2
Contest: Division 3
Contest: Division 4
Author: yash_daga
Tester: raysh07
Editorialist: iceknight1093
DIFFICULTY:
TBD
PREREQUISITES:
None
PROBLEM:
You’re given the skill levels of N batsmen and M bowlers (A_i and B_i, respectively).
Find the maximum possible sum of skill levels of a team of 11 players that includes at least 4 batsmen and at least 4 bowlers.
EXPLANATION:
First off, if N \lt 4 or M \lt 4 or N+M \lt 11, it’s impossible to pick a team at all.
Otherwise, it’s always possible to form a valid team, so we only need to maximize the sum of skill levels.
We need to choose at least 4 each of batsmen and bowlers, so do that first: pick the largest 4 values each from A and B.
This leaves us with 3 more people to be chosen, but now it doesn’t matter whether they’re batsmen or bowlers (i.e chosen from A or B).
So, take all the remaining (N-4) + (M-4) elements into a single list, and then choose the largest three elements of this list.
Finding the largest 3 or 4 elements of a list can be done quickly by sorting it.
TIME COMPLEXITY:
\mathcal{O}((N+M)\log ({N+M})) per testcase.
CODE:
Tester's code (C++)
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define INF (int)1e18
#define f first
#define s second
mt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count());
void Solve()
{
int n, m; cin >> n >> m;
vector <int> a(n);
for (auto &x : a) cin >> x;
vector <int> b(m);
for (auto &x : b) cin >> x;
if (n < 4 || m < 4 || (n + m) < 11){
cout << -1 << "\n";
return;
}
sort(a.begin(), a.end());
sort(b.begin(), b.end());
int ans = 0;
int t = 4;
while (t--){
ans += a.back();
a.pop_back();
}
t = 4;
while (t--){
ans += b.back();
b.pop_back();
}
vector <int> c;
for (auto x : a) c.push_back(x);
for (auto x : b) c.push_back(x);
sort(c.begin(), c.end());
t = 3;
while (t--){
ans += c.back(); c.pop_back();
}
cout << ans << "\n";
}
int32_t main()
{
auto begin = std::chrono::high_resolution_clock::now();
ios_base::sync_with_stdio(0);
cin.tie(0);
int t = 1;
// freopen("in", "r", stdin);
// freopen("out", "w", stdout);
cin >> t;
for(int i = 1; i <= t; i++)
{
//cout << "Case #" << i << ": ";
Solve();
}
auto end = std::chrono::high_resolution_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin);
cerr << "Time measured: " << elapsed.count() * 1e-9 << " seconds.\n";
return 0;
}
Editorialist's code (Python)
for _ in range(int(input())):
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
if min(n, m) < 4 or n+m < 11:
print(-1)
continue
a, b = sorted(a), sorted(b)
ans = sum(a[-4:]) + sum(b[-4:])
c = sorted(a[:-4] + b[:-4])
ans += sum(c[-3:])
print(ans)