匈牙利算法实现最优分配求解(C++ / Python)

设有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).")
        ####################################################################
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值