我开始在C ++中为分配问题做分支定界算法,但我找不到合适的解决方案。首先是分配问题的例子: Assignment problem
好的,所以每个人都可以被分配到一个工作,并且想法是将每个工作分配给一个人,以便所有工作以最快的方式完成。
到目前为止,这是我的代码:
#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);
}
}
我知道我可能会失控。我在开始时没有使用下限,我实际上有点混淆这个算法是如何工作的。因此,即使一步一步地通过算法也很有帮助。