Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int d7p1(const string& filename)
- {
- ifstream file(filename);
- string line;
- getline(file, line);
- stringstream iss(line);
- vector<int> crabs;
- for (int number; iss >> number;)
- {
- crabs.push_back(number);
- if (iss.peek() == ',')
- iss.ignore();
- }
- std::sort(crabs.begin(), crabs.end());
- int idx;
- if (crabs.size() % 2 == 1)
- idx = crabs[(crabs.size() + 1) / 2];
- else
- {
- int left = crabs[crabs.size() / 2 - 1];
- int right = crabs[crabs.size() / 2];
- idx = (int)((left + right) / 2);
- }
- int fuel = 0;
- for (const auto& crab : crabs)
- {
- fuel += (int)abs(crab - idx);
- }
- return fuel;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement