您可以通过将其公式化为最低成本的网络流量问题来最佳地解决此问题。
根据人员和项目的偏好设置成本。
(由于Networkx提供了最小成本流,但没有提供最大成本流,因此我将成本设置为负。)
例如,使用Networkx和Python:
import networkx as nxG=nx.DiGraph()prefs={'Tom':['Project1','Project2','Project3'], 'Dick':['Project2','Project1','Project3'], 'Harry':['Project1','Project3','Project1']}capacities={'Project1':2,'Project2':10,'Project3':4}num_persons=len(prefs)G.add_node('dest',demand=num_persons)A=[]for person,projectlist in prefs.items(): G.add_node(person,demand=-1) for i,project in enumerate(projectlist): if i==0: cost=-100 # happy to assign first choices elif i==1: cost=-60 # slightly unhappy to assign second choices else: cost=-30 # very unhappy to assign third choices G.add_edge(person,project,capacity=1,weight=cost) # Edge taken if person does this projectfor project,c in capacities.items(): G.add_edge(project,'dest',capacity=c,weight=0)flowdict = nx.min_cost_flow(G)for person in prefs: for project,flow in flowdict[person].items(): if flow: print person,'joins',project
在此代码中,Tom的第一选择是Project1,然后是Project2,然后是Project3。
容量字典指定每个项目可以加入的人数上限。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)