如何解决Kattis:“浇水草”间隔覆盖问题,为什么我的代码这么慢?
我正在练习,正在对此挑战进行python实现:https://open.kattis.com/problems/grass
它的工作方式应该是好的输出,但是它总是太慢。我尝试过移动一些东西,但似乎没有任何效果。我已经添加了很多代码,但是我试图遵循功能最少的代码片段的原则,以便有人可以自己运行它。
我使用一些解析将圆视为必须覆盖的较大间隔中的子间隔(头,尾)。
# Getmax is used in the algorithm to find the largest tail of all subintervals
def getmax(liste,t):
big = -1
start = None
indexOfNewT = 0
for n in range(len(liste)):
if liste[n][0] <= t:
if liste[n][1] >= big:
big = liste[n][1]
start = liste[n][0]
indexOfNewT = n
# In order to get a smaller list that i need to find a large tail in,I remove the elements that I add
del liste[indexOfNewT]
res = (start,big)
if start == None:
return None,None,None
return big,res,liste
# Here is the actual algorithm that solves the issue. 'Intervals' is a list of sublists which all
#contain n numbers of intervals [start,end]. Lowerbound,upperBound are numbers indicating length of
#Grass field (Lowerbound is always 0)
#I was wondering whether the sorting Could be done in a more cLever way?
def solver(lowerbound,upperBound,Intervals):
Intervals.sort(key=lambda x: x[1])
S = []
t = lowerbound
if (Intervals[len(Intervals)-1][1] < upperBound):
return -1
while t < upperBound:
# getmax,her leder vi efter den største hale på et interval,mens head
# på samme interval ikke er mere end det sidst addede element (t)
get,i,newlist = getmax(Intervals,t)
Intervals = newlist
if get is None:
return -1
S.append(i)
t = get
return len(S)
#method for converting circles to intervals with a head and a tail coordinate
def getB(a,c):
inter = abs(c * c - a * a)
# Here we actually parse the input,this method also calls the actual algorithm and provides output
#for every test case
def parse():
Innerintervals = []
# this is the loop that reads lines,if the line has more than three elements,it indicates a new
# test case is coming. The reading itself happens at O(n) i dont think i Could do better,Could I?
for line in sys.stdin:
current = line.split()
if (len(current)) >= 3:
if Innerintervals:
# the algorithm is directly executed and printed as a test case is read
print(solver(0,grassLen,Innerintervals))
grassLen = float(current[1])
width = float(current[2])
Innerintervals = []
else:
linesplit = line.split()
#Using a bit of pythagoras to get the places where the circle touches the edges of the field
# I use this to be able to treat this a a interval covering problem
position = int(linesplit[0])
radius = int(linesplit[1])
lenOfB = getB(width/2,radius)
IntervalMin = position - lenOfB
IntervalMax = position + lenOfB
Innerintervals.append([IntervalMin,IntervalMax])
# as a result of my loop being constructed a bit clumsy,the last element is executed here
print(solver(0,Innerintervals))
#running parse to starte the whole thing
parse()
我真的想获得一些提示,以防万一任何代码“很臭”,或者是否可以在可能出现一些明显错误的地方进行优化
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。