📌  相关文章
📜  最大化所有人的总利润

📅  最后修改于: 2021-04-29 05:38:39             🧑  作者: Mango

组织中有一个层次结构。要组织一个聚会。没有两个直属下属可以参加聚会。利润与每个人都息息相关。您必须使参加聚会的所有人员的总利润最大化。

层次结构
在一个层次化的组织中,所有员工(除头一个员工外)都是其他一些员工的下属。
员工仅直接向其上级报告。这允许灵活且有效的结构。

出于此问题的目的,可以将这种结构想象为一棵树,每个雇员都作为其节点。

例子:

Input: 
         15
       /   \
     10     12
    /  \   /  \
   26   4 7    9
Output: The Maximum Profit would be 15+12+26+9 = 62
The Parent 15 chooses sub-ordinate 12, 10 chooses 26 and 12 chooses 9.

Input:
        12
       / | \
      9 25 16
     /     / \
    13    13   9
Output: 12+25+13+13 = 63

方法:
给定每位员工的利润,我们必须找到最大金额,这样就不会邀请具有相同上级(父级)的两个员工(节点)。如果每个员工都选择贡献最大的下属,就可以实现这一目标。
在该程序中,公司的层次结构以字典的形式实现,密钥为唯一的员工ID,数据为[与此员工相关的利润,[直属下属列表] ]。
对于每位雇员,关联最高利润的下属将被添加到总利润中。此外,始终邀请总干事。

def getMaxProfit(hier):
    # The head has no competition and therefore invited
    totSum = hier[1][0]
    for i in hier:
        currentSuperior = hier[i]
        selectedSub = 0
        # select the subordinate with maximum
        # value of each superior
        for j in currentSuperior[1]:
            if(hier[j][0] > selectedSub):
                selectedSub = hier[j][0]
        totSum += selectedSub
    return totSum
  
# driver function
def main():
    # Define the Organization as a Dictionary
    # Index : [Profit, List of Employees]
        # Same as example 1 given above
# 1:15
#       /     \
# 2:10    3:12
#    /   \    /   \
# 4:26 5:4 6:7  7:9
  
    organization = {1:[15, [2, 3]],
                    2:[10, [4, 5]], 3:[12, [6, 7]],
                    4:[26, []], 5:[4, []], 6:[7, []], 7:[9, []]}
    maxProfit = getMaxProfit(organization)
    print(maxProfit)
      
main()
输出:
62