Solution 1
Explanation
We can use a greedy approach to solve this problem. First, we sort the applicants and apartments. We keep two pointers and (initialized to 0), which keep track of the current index of the applicant and apartment we are looking at respectively. Then, while there are more applicants and apartments to look through, we repeatedly check the following:
- If , we have found a suitable apartment for the current applicant. Thus, we increment , , and our answer.
- Otherwise, is either too big or too small for . We can increment or accordingly.
Implementation
Time Complexity:
n, m, tolerance = map(int, input().split())applicants = list(map(int, input().split()))apartments = list(map(int, input().split()))applicants.sort()apartments.sort()i = 0 # Applicant pointerj = 0 # Apartment pointerans = 0while i < n and j < m:
Solution 2
Explanation
We can use C++'s std::multiset to find an apartment that is in the range of an applicant's desired size.
- Using lower bound, we can find the smallest apartment the applicant can tolerate.
- If none exists, we do nothing.
- Otherwise, we remove it from the multiset and add one to our answer. Removing it makes sure another applicant cannot take it.
Sorting the applicants by results in the desired apartment sizes for each applicant being sorted in increasing value. This is built into the multiset.
Besides this, the spirit of the greedy algorithm is the same as in the previous solution.
Implementation
Time Complexity:
#include <bits/stdc++.h>using namespace std;int main() {int n, m, k;cin >> n >> m >> k;multiset<int> desired;for (int i = 0; i < n; i++) {
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!