Last active
August 29, 2015 14:08
-
-
Save jose-villegas/3bbf68dfc8bc7a564309 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <algorithm> | |
#include <tuple> | |
#include <vector> | |
#include <numeric> | |
using namespace std; | |
bool lessThan(pair<int, int> const &a, pair<int, int> const &b) { return a.first < b.first; } | |
int calculateCost(vector <pair<int, int> > deposits, vector<int> collectorsPos, int smallestCost) | |
{ | |
int currentCost = 0, i = 0; | |
vector <pair<int, int> >::iterator it = deposits.begin(); | |
do { | |
if (deposits.begin() + i == it) { | |
it = deposits.begin() + distance(collectorsPos.begin(), find(collectorsPos.begin() + i + 1, collectorsPos.end(), 1)); | |
} | |
if (collectorsPos[i] == 0) { | |
(*it).second += deposits[i].second; | |
currentCost += deposits[i].second * ((*it).first - deposits[i].first); | |
} | |
} while (++i < deposits.size() && smallestCost > currentCost); | |
return currentCost; | |
} | |
int main() | |
{ | |
vector <pair<int, int> > deposits; | |
vector <int> collectorPos; | |
vector <int> results; | |
int currentVal = 0; | |
int numDeposits = -1; | |
int numCollectors = -1; | |
while (numDeposits != 0 || numCollectors != 0) { // Read User Input | |
cin >> numDeposits >> numCollectors; | |
if (numDeposits > 0 && numCollectors > 0 && numDeposits <= 10.0e4 && numDeposits >= numCollectors) { // Validate User Input | |
int lowestCost = std::numeric_limits<int>::max(); | |
collectorPos.resize(numDeposits); | |
fill(collectorPos.end() - numCollectors, collectorPos.end(), 1); | |
for (int i = 0; i < numDeposits; i++) { | |
pair<int, int> currentDeposit; | |
cin >> currentDeposit.first >> currentDeposit.second; | |
auto it = lower_bound(deposits.begin(), deposits.end(), currentDeposit, lessThan); // Sorted Vector Per Distance | |
deposits.insert(it, currentDeposit); | |
} | |
do { | |
currentVal = calculateCost(deposits, collectorPos, lowestCost); | |
lowestCost = lowestCost > currentVal ? currentVal : lowestCost; | |
} while (next_permutation(collectorPos.begin(), collectorPos.end() - 1)); | |
results.push_back(lowestCost); | |
deposits.clear(); | |
collectorPos.clear(); | |
} else if (numDeposits != numCollectors != 0) { cout << "Invalid Input" << endl; } | |
} | |
for_each(results.begin(), results.end(), [](int a) { cout << a << endl;}); | |
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); cin.get(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment