在python中提交Kattis问题时出现运行错误:我可以猜出数据结构



我现在正在尝试提交我对Kattis上以下问题的解决方案:我可以猜出数据结构!然而,我一直得到一个运行时错误;我想不出有什么地方会出错,因为它对我所有的输入都有效。下面是我的解决方案:

import heapq, sys
def throwin(q,s,h,x, results):
if results[0]:
q.append(x)
if results[1]:
s.append(x)
if results[2]:
heapq.heappush(h, -x)
return (q,s ,h )
def printstructures(l):
for j in l:
if j[0] and j[1] or j[0] and j[2] or j[1] and j[2]:
print("not sure")
elif not j[0] and not j[1] and not j[2]:
print("impossible")
elif j[0]:
print("queue")
elif j[1]:
print("stack")
else:
print("priority queue")
def main():
results_global = []
stackops = []
current = []
while True:
try:
line = input()
if len(line) == 1:
if len(current) != 0:
stackops.append(current)
current = []
else:
current.append(tuple(map(int, line.split(" "))))
except EOFError:
break
stackops.append(current)
for op in stackops:
q,s,h = [],[],[]
heapq._heapify_max(h)
results = [True, True, True]
for i in range(len(op)):
o, x = op[i]
if o == 1:
q,s,h = throwin(q,s,h,x, results)
else:
if len(q) == 0 or q[0] != x:
results[0] = False
else:
q.pop(0)
if len(s) == 0 or s[-1] != x:
results[1] = False
else:
s.pop()
if len(h) == 0 or h[0] != -x :
results[2] = False
else:
heapq.heappop(h)
if i == len(op)-1:
results_global.append(results)
printstructures(results_global)
if __name__ == "__main__":
main()

我想知道是否有人可以在正确的方向上给我一把,指出我的想法是错误的,或者如果我犯了一个错误,我忽略了。

对于这个问题,我有相同的运行时错误问题,我认为它与python输入/输出EOFError有关。我无法找出具体的错误,但我只是在我的整个程序中执行了一个try/except传递,kattis接受了解决方案。

import sys
try:
def solve(n):
stack = []
queue = []
priority_queue = []
type_ds = [True, True, True]
for i in range(n):
command, element = map(int, input().split())
if command == 1:
if type_ds[0] != False:
stack.append(element)
if type_ds[1] != False:
queue.append(element)
if type_ds[2] != False:
priority_queue.append(element)
elif command == 2:
if type_ds[0] != False:
if len(stack) == 0:
return "impossible"
if element != stack.pop():
type_ds[0] = False
stack.clear()
if type_ds[1] != False:
if len(queue) == 0:
return "impossible"
if element != queue.pop(0):
type_ds[1] = False
queue.clear()
if type_ds[2] != False:
if len(priority_queue) == 0:
return "impossible"
priority_queue.sort(reverse=True)
if element != priority_queue.pop(0):
type_ds[2] = False
priority_queue.clear()

if type_ds.count(True) > 1:
return "not sure"
elif type_ds.count(True) == 0:
return "impossible"
else:
if type_ds[0] == True:
return "stack"
elif type_ds[1] == True:
return "queue"
else:
return "priority queue"
for line in sys.stdin:
if line.strip() == "":
break
n = int(line.strip())
print(solve(n))
except:
pass

你确定你跳出了while循环吗?它在您的计算机上运行正常吗?在有时间限制的竞争性编程中,使用try/except语句通常不是一个好主意,它会大大降低脚本的速度。

最新更新