簡體   English   中英

如何將O(N * M)優化為O(n ** 2)?

[英]How to optimize an O(N*M) to be O(n**2)?

我正在嘗試解決USACO的奶牛問題。 問題陳述在這里: https : //train.usaco.org/usacoprob2?S=milk2&a=n3lMlotUxJ1

給定一系列二維數組形式的間隔,我必須找到最長的間隔和沒有擠奶的最長間隔。

防爆。 給定數組[[500,1200],[200,900],[100,1200]] ,由於連續擠奶,最長間隔為1100,沒有擠奶的最長間隔為0,因為沒有休息時間。

我曾嘗試查看使用字典是否會減少運行時間,但並沒有取得太大的成功。

f = open('milk2.in', 'r')
w = open('milk2.out', 'w')

#getting the input
farmers = int(f.readline().strip())
schedule = []
for i in range(farmers):
    schedule.append(f.readline().strip().split())


#schedule = data
minvalue = 0
maxvalue = 0

#getting the minimums and maximums of the data 
for time in range(farmers):
    schedule[time][0] = int(schedule[time][0])
    schedule[time][1] = int(schedule[time][1])
    if (minvalue == 0):
        minvalue = schedule[time][0]
    if (maxvalue == 0):
        maxvalue = schedule[time][1]
    minvalue = min(schedule[time][0], minvalue)
    maxvalue = max(schedule[time][1], maxvalue)

filled_thistime = 0
filled_max = 0

empty_max = 0
empty_thistime = 0

#goes through all the possible items in between the minimum and the maximum
for point in range(minvalue, maxvalue):
    isfilled = False
    #goes through all the data for each point value in order to find the best values
    for check in range(farmers):
        if point >= schedule[check][0] and point < schedule[check][1]:
            filled_thistime += 1
            empty_thistime = 0
            isfilled = True
            break
    if isfilled == False:
        filled_thistime = 0
        empty_thistime += 1
    if (filled_max < filled_thistime) : 
        filled_max = filled_thistime 
    if (empty_max < empty_thistime) : 
        empty_max = empty_thistime 
print(filled_max)
print(empty_max)
if (filled_max < filled_thistime):
    filled_max = filled_thistime

w.write(str(filled_max) + " " + str(empty_max) + "\n")
f.close()
w.close()

該程序工作正常,但我需要減少運行時間。

如評論中所述,如果對輸入進行排序,則復雜度可能為O(n),如果不是這種情況,我們需要首先對其進行排序,並且復雜度為O(nlog n):

lst = [ [300,1000],
[700,1200],
[1500,2100] ]

from itertools import groupby

longest_milking = 0
longest_idle = 0

l = sorted(lst, key=lambda k: k[0])

for v, g in groupby(zip(l[::1], l[1::1]), lambda k: k[1][0] <= k[0][1]):
    l = [*g][0]
    if v:
        mn, mx = min(i[0] for i in l), max(i[1] for i in l)
        if mx-mn > longest_milking:
            longest_milking = mx-mn
    else:
        mx = max((i2[0] - i1[1] for i1, i2 in zip(l[::1], l[1::1])))
        if mx > longest_idle:
            longest_idle = mx

# corner case, N=1 (only one interval)
if len(lst) == 1:
    longest_milking = lst[0][1] - lst[0][0]

print(longest_milking)
print(longest_idle)

打印:

900
300

輸入:

lst = [ [500,1200],
        [200,900],
        [100,1200] ]

打印:

1100
0

一種不那么漂亮但更有效的方法是像一個自由列表一樣解決此問題,盡管由於范圍可能會重疊,所以它有些棘手。 此方法僅需要循環遍歷輸入列表一次。

def insert(start, end):
    for existing in times:
        existing_start, existing_end = existing
        # New time is a subset of existing time
        if start >= existing_start and end <= existing_end:
            return
        # New time ends during existing time
        elif end >= existing_start and end <= existing_end:
            times.remove(existing)
            return insert(start, existing_end)
        # New time starts during existing time
        elif start >= existing_start and start <= existing_end:
            # existing[1] = max(existing_end, end)
            times.remove(existing)
            return insert(existing_start, end)
        # New time is superset of existing time
        elif start <= existing_start and end >= existing_end:
            times.remove(existing)
            return insert(start, end)
    times.append([start, end])

data = [
    [500,1200],
    [200,900],
    [100,1200] 
]

times = [data[0]]
for start, end in data[1:]:
    insert(start, end)

longest_milk = 0
longest_gap = 0
for i, time in enumerate(times):
    duration = time[1] - time[0]
    if duration > longest_milk:
        longest_milk = duration
    if i != len(times) - 1 and times[i+1][0] - times[i][1] > longest_gap:
        longes_gap = times[i+1][0] - times[i][1]

print(longest_milk, longest_gap)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM