
代碼:
#!/usr/bin/env python
import sys
sys.setrecursionlimit(1000000000)
# N is the number of available days.
N = None
# F is the amount of fuel available.
F = None
# C contains the fuel needed to open a portal on each day.
C = [None for x in range(100005)]
answer = None
# Open the input and output files.
input_file = open("spacein.txt", "r")
output_file = open("spaceout.txt", "w")
# Read the value of N and F.
input_line = input_file.readline().strip()
N, F = map(int, input_line.split())
# Read the cost to open a portal on each day.
for i in range(0, N):
C[i] = int(input_file.readline().strip())
fuel = []
for i in range(0, N):
fuel.append(C[i])
print(fuel)
final = []
for i in range(0, len(fuel)-2):
for j in range(i 1, len(fuel)):
if fuel[i] fuel[j] < F or fuel[i] fuel[j] == F:
final.append(fuel.index(fuel[j])-fuel.index(fuel[i]))
print(fuel.index(fuel[i]), fuel.index(fuel[j]))
else:
pass
if len(fuel) > 2:
answer = (max(final) 1)
else:
answer = -1
# Write the answer to the output file.
output_file.write("%d\n" % (answer))
# Finally, close the input/output files.
input_file.close()
output_file.close()
uj5u.com熱心網友回復:
第二個樣本輸入有更深入的日常消費清單:
F = 14
C = [12, 8, 2, 16, 4, 6, 10]
請注意,即使 F 更大,您也絕對不會在當天開始消費 16,因為較早的日子成本更低,付出的更多。由于這個原因,只有 12、8 和 2 天是可行的開始日。
因此,隨著時間的流逝,不斷減少消費條目及其原始索引(即日期)。并且對于盡可能結束的每一天,二進制搜索該串列。例如,對于消費 4 作為結束日的那一天,您可以負擔 14-4=10 作為開始日。在 [12, 8, 2] 中二分搜索 10 以找到 8。
接受的代碼(我否定了消耗值,因為bisect想要一個遞增的串列):
from bisect import bisect_left
with open('spacein.txt') as f:
_, F, *C = map(int, f.read().split())
S = []
I = []
best = -1
for i, c in enumerate(C):
j = bisect_left(S, c - F)
if j < len(S):
best = max(best, i - I[j] 1)
if not S or c < -S[-1]:
S.append(-c)
I.append(i)
with open('spaceout.txt', 'w') as f:
print(best, file=f)
uj5u.com熱心網友回復:
我認為您可以通過簡單地更改行來使您的程式更快:
C = [None for x in range(100005)]
到:
C = []
然后,在您的回圈中,更改:
C[i] = int(input_file.readline().strip())
到:
C.append(int(input_file.readline().strip()))
因為那樣你不會回圈 100005 次只是為了將 None 值放入 C 陣列中。另外,我根本不明白為什么你需要這個C陣列,因為你只用它來填充fuel陣列?我只是將每天的門戶成本直接讀入fuel陣列,這樣您就可以減少冗余,這樣您的代碼中就會少一個 N 回圈。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/400683.html
上一篇:如何生成二進制檔案
下一篇:使用堆演算法生成排列
