PROBLEM LINK:
Practice
Contest: Division 1
Contest: Division 2
Contest: Division 3
Contest: Division 4
Author: raysh07
Tester: sushil2006
Editorialist: raysh07
DIFFICULTY:
Cakewalk
PREREQUISITES:
None
PROBLEM:
Chef has N options for first layer, A_1, A_2, \ldots, A_N, and M options for second layer, B_1, B_2, \ldots, B_M. A cake is valid when the first layer has a strictly larger size than the second layer. How many cakes can Chef make?
EXPLANATION:
We can simply run a nested for-loop over all options of first layer (say i), and all options of second layer (say j), and then add 1 to answer if A_i > B_j.
The inner for loop will run M times, and the outer for loop will run N times, giving a total time complexity of O(N \cdot M).
It is also possible to solve the problem in O(N + M) by sorting the arrays and then using 2 pointers, but it was unnecessary.
TIME COMPLEXITY:
\mathcal{O}(N \cdot M) per testcase.
CODE:
Editorialist's Code (C++)
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define INF (int)1e18
mt19937_64 RNG(chrono::steady_clock::now().time_since_epoch().count());
void Solve()
{
int n, m; cin >> n >> m;
vector <int> a(n), b(m);
for (auto &x : a) cin >> x;
for (auto &x : b) cin >> x;
int ans = 0;
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++) if (a[i] > b[j]){
ans++;
}
}
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;
}```