I am trying to solve this puzzle: Shipping Coding Puzzle. This is the code I have come up so far:
#include <fcntl.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <sstream>
#include <set>
using namespace std;
struct Container
{
Container(int c, int w) : cost(c), weight(w){}
int cost;
int weight;
bool operator<(const Container& c) const
{
return double(cost)/weight < double(c.cost)/c.weight;
}
};
int main(int argc, char** argv)
{
int fd = open(argv[1], O_RDONLY);
char* pContent = (char*)mmap(NULL, 128 * sizeof(int), PROT_READ, MAP_PRIVATE, fd, 0);
pContent += 8;
stringstream ss(pContent);
int unload = 0;
ss >> unload;
set<Container> containers;
int cost = 0, weight = 0;
while(ss >> cost)
{
ss >> weight;
containers.insert(Container(cost, weight));
}
const Container& best = *containers.begin();
cost = best.cost * ceil(double(unload)/best.weight);
printf("%d\n", cost);
return 0;
}
I know there may be some bugs in this logic. But my question is not related to the logic. When I submit this code it successfully runs but the score I get is less as it says the number minor page faults is 409
. When I see the leader board somebody has submitted a C++ code with minor page faults 69
. Is there any way I can control these minor page faults? may be using some g++ flags ? Right now my make file is very simple: g++ -o MyExe MyExe.cc
.
You're at the mercy of whatever algorithm and runtime environment Gild use for judging these. I think that compiler flags are probably a red herring; I suspect that submitting in "release mode" turns on -O2 or -O3 for you.
I suspect it's a question of optimising for memory use, possibly memory locality. That stringstream and set could get very expensive, for example; in your shoes I'd start looking to see whether there was another way, perhaps with a more tailored algorithm.