我已经在 C++11 中实现了这个SPOJ 问题的解决方案,并且在使用clang
. SPOJ 的提交使用g++
会在消息中引发运行时错误invalid pointer
。我已经把它缩小到这条线:
studentNumberToRequestedBedroomsMap.clear();
我从其他答案中了解到,当被释放的指针不是由 获得的指针时会发生此错误malloc
,但是由于我对 C++ 还是很陌生,我不确定如何使用该信息来解决此问题。我很感激帮助解决这个问题。
#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();
}
}
}