python找图找色-python – 找到“好”邻居的算法 – 图着色?

评论中已经提到,这个问题相当于旅行商问题.我想详细说明一下:

每个人都相当于一个顶点,并且边缘位于顶点之间,这些顶点代表可以相互对接的人.现在,找到可能的座位安排相当于在图中找到哈密顿路径.

所以这个问题就是NPC.最天真的解决方案是尝试所有可能的排列,从而导致O(n!)运行时间.有许多众所周知的方法比O(n!)表现更好,并且可以在网上免费获得.我想提一下Held-Karp,它运行在O(n ^ 2 * 2 ^ n)并且非常直接代码,这里是python:

#graph[i] contains all possible neighbors of the i-th person

def held_karp(graph):

n = len(graph)#number of persons

#remember the set of already seated persons (as bitmask) and the last person in the line

#thus a configuration consists of the set of seated persons and the last person in the line

#start with every possible person:

possible=set([(2**i,i) for i in xrange(n)])

#remember the predecessor configuration for every possible configuration:

preds=dict([((2**i,i),(0,-1)) for i in xrange(n)])

#there are maximal n persons in the line - every iterations adds a person

for _ in xrange(n-1):

next_possible=set()

#iterate through all possible configurations

for seated,last in possible:

for neighbor in graph[last]:

bit_mask=2**neighbor

if (bit_mask&seated)==0: #this possible neighbor is not yet seated!

next_config=(seated|bit_mask,neighbor)#add neighbor to the bit mask of seated

next_possible.add(next_config)

preds[next_config]=(seated,last)

possible=next_possible

#now reconstruct the line

if not possible:

return []#it is not possible for all to be seated

line=[]

config=possible.pop() #any configuration in possible has n person seated and is good enough!

while config[1]!=-1:

line.insert(0,config[1])

config=preds[config]#go a step back

return line

免责声明:此代码未经过适当测试,但我希望您能得到它的要点.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值