I've implemented a solution to this SPOJ problem in C++11 and it compiles perfectly when using clang
. SPOJ's submission uses g++
which throws a runtime error with the message invalid pointer
. I've narrowed it down to the line:
studentNumberToRequestedBedroomsMap.clear();
I've understood from other answers that this error occurs when the pointer being freed is not one that was obtained by malloc
, but as I'm still rather new to C++, I'm not sure how to use that information to solve this problem. I'd appreciate help fixing this issue.
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <set>
#include <algorithm>
#define INDEX(bedNumber) (bedNumber - 1)
int main() {
std::string input = "3\n"
"3 3\n"
"1 1\n"
"2 1\n"
"2 2\n"
"3 2\n"
"3 3\n"
"0 0\n"
"4 3\n"
"1 1\n"
"1 3\n"
"2 1\n"
"3 1\n"
"3 2\n"
"4 2\n"
"0 0\n"
"4 2\n"
"1 1\n"
"1 2\n"
"2 1\n"
"2 2\n"
"3 1\n"
"3 2\n"
"4 1\n"
"4 2\n"
"0 0";
std::istringstream inputString(input);
int lineNumber;
std::string line;
std::set<int> assignedBedrooms;
std::vector<std::vector<int>> studentNumberToRequestedBedroomsMap;
std::vector<int> bedroomDemand;
while (getline(inputString, line)) {
++lineNumber;
std::stringstream lineStream(line);
if (lineNumber == 1) {
continue;
}
if (bedroomDemand.empty()) {
int numberOfStudents;
lineStream >> numberOfStudents;
int numberOfBeds;
lineStream >> numberOfBeds;
bedroomDemand.resize(numberOfBeds);
std::fill(bedroomDemand.begin(), bedroomDemand.end(), 0);
// initialize studentNumberToRequestedBedroomsMap
studentNumberToRequestedBedroomsMap.resize(numberOfStudents);
std::fill(studentNumberToRequestedBedroomsMap.begin(),studentNumberToRequestedBedroomsMap.end(),std::vector<int>());
continue;
}
int bedroomNumber;
lineStream >> bedroomNumber;
int studentNumber;
lineStream >> studentNumber;
if (studentNumber != 0) {
studentNumberToRequestedBedroomsMap[studentNumber-1].push_back(
bedroomNumber);
bedroomDemand[INDEX(bedroomNumber)]++;
} else {
// End of test case
// Sort bedRequested in order of least in-demand to most in-demand
for (auto &item : studentNumberToRequestedBedroomsMap) {
std::sort(
item.begin(), item.end(),
[&bedroomDemand](int bedroomNumberLeft, int bedroomNumberRight) {
return bedroomDemand[INDEX(bedroomNumberLeft)] <
bedroomDemand[INDEX(bedroomNumberRight)];
});
}
// Start assigning rooms to students starting with the least in-demand
// room requested.
for (auto item : studentNumberToRequestedBedroomsMap) {
for (auto bedroomNumber : item) {
auto result = assignedBedrooms.insert(bedroomNumber);
if (result.second) {
break;
}
}
}
std::cout << assignedBedrooms.size() << std::endl;
assignedBedrooms.clear();
bedroomDemand.clear();
studentNumberToRequestedBedroomsMap.clear();
}
}
}