设有5人(甲乙丙丁戊),独立完成5项任务(ABCDE),各自所需时间如表所示。
找到一个组合,使5项任务所需总体时间最短。
通过匈牙利算法,得到该组合的解,如表所示。
在算法中,可以用数组 (1,2,4,3,0) 作为该解的一种表示形式。理论可以参照本文。
部分C++(完整代码):
/**
* @brief get an example of input cost matrix
* @return Mat1f: cost matrix
*/
Mat1f red::Hungary::getExpInput()
{
const int w = 5;
const int h = 5;
const int size = w * h;
static float exp_arr[size] =
{ 12, 7, 9, 7, 9,
8, 9, 6, 6, 6,
7, 17, 12, 14, 9,
15, 14, 6, 6, 10,
4, 10, 7, 10, 9
};
Mat1f exp_mat = Mat(h, w, CV_32FC1, exp_arr);
return exp_mat;
}
/**
* @brief run any examples for these algorithms
*/
void red::algorithm::Examples()
{
/************************************* Hungary ********************************/
Mat1f exp_cost = red::Hungary::getExpInput();
Mat1i indices = red::algorithm::getCostMatchings(exp_cost);
cout << "Exp.2 Hungary Result is " << indices << ", expect(1,2,4,3,0)." << endl;
}
部分Python(完整代码)
@staticmethod
def getExpInput():
'''
brief: get an example of input cost matrix
:return: array, cost matrix
'''
exp_arr = np.array([[12, 7, 9, 7, 9],
[ 8, 9, 6, 6, 6],
[ 7, 17, 12, 14, 9],
[15, 14, 6, 6, 10],
[ 4, 10, 7, 10, 9]],
dtype=np.float)
return exp_arr
@staticmethod
def Examples():
'''
brief: run any examples for this algorithm
:return: none
'''
####################################################################
############################# Hungary ##############################
exp_cost = Hungary.getExpInput()
indices = algorithm.getCostMatchings(exp_cost)
print("Exp.2 Hungary Result is", indices, ", expect(1,2,4,3,0).")
####################################################################