我有一个城市清单。每个城市都有一个列表,其中包含前往所有其他城市的费用。
每个城市都有不同的产品。我想以最便宜的价格在城市之间穿梭,并得到我想要的所有产品。
每次我走到城市时,我都会回到起点,但是我不算回去的费用。
城市1的旅行费用:[7、9、9、21、16、15、30、21]
每个城市拥有的产品: -城市0:A, -城市1:P,A -城市2:T,C -城市3:W,C -城市4:O,T,C -城市5:O A -城市6:O -城市7:P,O
如果我从城市1开始,并且想要获得A,T和W,我可以从城市1到城市3(获得W),然后从城市1到城市4(获得T)。并从城市1到达城市5(获得A)。
费用将为21 + 16 + 15
我尝试在此处遵循解决方案:
Finding cheapest combination of items with conditions on the selection
这是我到目前为止尝试过的:
# I call find_best(startIndex(i),goal('allProducts'),costs(x.grid_),cities(cities_))
for x in cities_:
x.setGrid()
for y in pyastar.find_best(i,allProducts,x.grid_,cities_):
print(y)
def find_best(start,goal, costs , cities):
# state is tuple (cost, gathered, state)
heap = [(0, set(),[])]
visited = []
print(costs)
while heap:
cost, gathered , paths= heapq.heappop(heap)
gathered = cities[start].p
for x in visited:
if paths == x:
continue # already seen this combination
visited.append(paths)
if gathered == goal: # found one!
yield (cost, gathered , paths)
i = 0
for city in costs:
if len(cities[i].p - gathered) != 0:
new_cost = cost + city # increase cost
for x in cities[i].p:
if(x not in gathered):
gathered.add(x)
paths.append(i)
heapq.heappush(heap, (new_cost, gathered ,paths)) # push to heap
i = i + 1
感谢您的帮助