对于算法竞赛训练(不是家庭作业),我们在过去一年中收到了这个问题。将其发布到此站点是因为其他站点需要登录。
这就是问题:http://pastehtml.com/view/c5nhqhdcw.html http://pastehtml.com/view/c5nhqhdcw.html
Image didn't work so posted it here:
它必须在不到一秒的时间内运行,我只能考虑最慢的方法,这就是我尝试过的:
with open('islandin.txt') as fin:
num_houses, length = map(int, fin.readline().split())
tot_length = length * 4 # side length of square
houses = [map(int, line.split()) for line in fin] # inhabited houses read into list from text file
def cost(house_no):
money = 0
for h, p in houses:
if h == house_no: # Skip this house since you don't count the one you build on
continue
d = abs(h - house_no)
shortest_dist = min(d, tot_length - d)
money += shortest_dist * p
return money
def paths():
for house_no in xrange(1, length * 4 + 1):
yield house_no, cost(house_no)
print house_no, cost(house_no) # for testing
print max(paths(), key=lambda (h, m): m) # Gets max path based on the money it makes
我现在正在做的是遍历每个位置,然后遍历该位置的每个有人居住的房屋以找到最大收入位置。
伪代码:
max_money = 0
max_location = 0
for every location in 1 to length * 4 + 1
money = 0
for house in inhabited_houses:
money = money + shortest_dist * num_people_in_this_house
if money > max_money
max_money = money
max_location = location
这太慢了,因为它的时间复杂度为 O(LN),并且对于最大的测试用例不会在一秒内运行。有人可以简单地告诉我如何在最短的运行时间内完成它(除非你愿意,否则不需要代码),因为这已经困扰我很多年了。
编辑:一定有一种方法可以在小于 O(L) 的时间内做到这一点,对吧?