I am trying to solve the apartments problem on CSES. VERY new to coding and not looking for a solution.. just help with troubleshooting.
https://cses.fi/problemset/task/1084/.
I want to match n applicants to m apartments based on cost, given a list of each. It works with sample inputs, but many tests still fail. I think the issue is with my vector manipulation in the nested for loop.
Example of a test that fails
n 10
m 10
k 10
n integers 90 41 20 39 49 21 35 31 74 86
m integers 14 24 24 7 82 85 82 4 60 95
Expected result for aptsMatched: 6, my result: 3
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m, k, aptfill, aptsize;
int aptsMatched = 0;
vector<int> desiredSize;
vector<int> apts;
int b=0;
cin >> n;
cin >> m;
cin >> k;
I'm sure there's a better way to do this.. but I'm brand new and attempted to do this in an intuitive manner. Was able to successfully fill my vectors with the inputs below.
for (int i = 0; i < n; i++) {
cin >> aptfill;
desiredSize.push_back(aptfill);
sort(desiredSize.begin(), desiredSize.end());
reverse(desiredSize.begin(), desiredSize.end());
}
for (int i = 0; i < m; i++) {
cin >> aptsize;
apts.push_back(aptsize);
sort(apts.begin(), apts.end());
reverse(apts.begin(), apts.end());
}
I'm attempting to iterate through the apts vector 3x, each time holding the apts index value constant while iterating through the desiredSize vector indices. Suspect something is wrong with the nested loop - either j<desiredSize.size(); or flawed logic in the if statement... or even with the erase function. My questions are: how can I test what's going wrong here? is there possibly a better container?
for (int i = 0; i < m; i++) {
for (int j = 0; j < desiredSize.size(); j++) {
if (abs(apts[b] - desiredSize[j]) <= k) {
desiredSize.erase(desiredSize.begin() + j);
b++;
aptsMatched++;
break;
}
else {
continue;
}
}
}
cout << aptsMatched;
}
I realize this code is pretty hideous, and that there are much faster ways to achieve the same idea. I'd first like to understand this methodology (if it's not completely flawed to start with), but am open to more effective ways to approach this problem too.
Thanks