1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
|
#include "Matrix.h"
// Program to solve Job Assignment problem
// using Branch and Bound
#include <limits.h>
#include <vector>
#include <algorithm>
using namespace std;
template<class T>
NUM getCost(Matrix& matrix, size_t x, size_t y, vector<bool>& colUsed);
void run(Matrix& matrix, vector<size_t>& assignedJobs);
int main()
{
Matrix matrix;
matrix.setMatrix(N);
matrix.print();
vector<size_t> assignedJobs;
run(matrix, assignedJobs);
cout << assignedJobs[0];
/*
cout << "size:E " << v.size() << endl;
for (vector<NUM>::iterator i = v.begin(); i != v.end(); i++)
{
cout << *i << endl;
}
*/
return 0;
}
// remember to use x only LOCALLY!!!
NUM getCost(Matrix& matrix, size_t x, size_t y, vector<bool>& colUsed)
{
// pathCost
NUM pathCost = matrix.matrix[x++][y];
for (size_t col = 0; col < matrix.size(); col++)
{
if (!colUsed.at(col))
{
NUM min =
#if defined NUM_INT
INT_MAX;
#endif
#if defined NUM_DBL
DBL_MAX;
#endif
size_t row = x;
for (; row < matrix.size(); row++)
{
if (min > matrix.matrix[row][col])
{
min = matrix.matrix[row][col];
}
}
pathCost += min;
}
}
return pathCost;
}
void run(Matrix& matrix, vector<size_t>& assignedJobs)
{
// array of used columns
vector<bool> colUsed;
for (size_t i = 0; i < matrix.size(); i++)
{
colUsed.push_back(false);
}
for (size_t row = 0; row < matrix.size(); row++)
{
size_t col = 0;
// bombona
while (colUsed.at(col++)); col--;
// choose the best job for the current worker
vector<NUM> jobs;
// get all the job costs from which to choose the smallest
// row++
jobs.push_back(getCost(matrix, col, row, colUsed));
// iterator at the position of the smallest element of jobs
vector<NUM>::iterator i_min = min_element(jobs.begin(), jobs.end());
// index of the smallest element in jobs
size_t index = (size_t)distance(jobs.begin(), i_min);
colUsed.at(index) = true;
assignedJobs.push_back(index);
}
}
|