Codeforces 461A超时问题

24 views
Skip to first unread message

吴悦凡

unread,
Dec 8, 2017, 4:54:40 AM12/8/17
to cs101pku
和题目语言描述无关,下面的代码都是正确的,请直接分析两种代码的差别就可以。

以下是正确但超时的代码:
n = int(input())
a
= [int(i) for i in input().split()]
a
.sort()
out = sum(a)
for i in range(n-1):
   
out += sum(a)
   
del a[0]
 
print(out)

错误信息:
Test: #7, time: 2000 ms., memory: 10908 KB, exit code: -1, checker exit code: 0, verdict: TIME_LIMIT_EXCEEDED
Input
300000

2 9 6 4 2 2 7 9 10 1 7 6 6 10 10 5 4 1 9 5 2 10 10 7 1 8 2 5 4 7 8 2 8 2 2 5 10 5 10 2 9 1 4 6 4 10 8 8 10 4 6 9 9 2 5 6 3 5 5 8 10 1 7 1 2 10 1 3 6 10 9 10 7 9 9 1 7 5 4 1 4 4 2 9 10 6 4 10 9 6 8 2 3 2 7 9 9 1 4 7 8 9 7 3 10 8 2 10 8 3 3 7 10 10 7 10 7 3 3 2 7 6 8 10 3 2 5 8 8 5 4 6 8 6 2 2 10 8 9 5 7 10 7 5 2 7 3 6 6 4 4 10 2 6 1 10 1 4 2 1 4 1 3 1 9 10 2 1 3 3 1 2 5 7 9 6 10 9 7 3 2 1 7 8 7 8 10 1 10 10 3 4 2 9 9 1 10 8 10 8 4 1 7 1 10 2 7 4 3 7 1 6 8 4 5 1 4 1 3 2 5 1 10 4 6 3 8 4 7 8 2 10 2 5 ...
 
换了一种方法,以下是可以通过的代码:
n = int(input())
a
= [int(i) for i in input().split()]
a
.sort()
out = sum(a)
for i in range(n):
   
out += (i+1)*a[i]
out -= a[n-1]
 
print(out)

求问:同样是一层for循环,为什么一种就超时,另一种就没有超时?
谢谢!

Hongfei Yan

unread,
Dec 8, 2017, 5:41:33 AM12/8/17
to cs10...@googlegroups.com
sum(a)本身是一个循环呀。超时的相当于双重循环了。

--
您收到此邮件是因为您订阅了Google网上论坛上的“cs101pku”群组。
要退订此群组并停止接收此群组的电子邮件,请发送电子邮件到cs101pku+unsubscribe@googlegroups.com
要发帖到此群组,请发送电子邮件至cs101pku@googlegroups.com
访问此群组:https://groups.google.com/group/cs101pku
要查看更多选项,请访问https://groups.google.com/d/optout

Reply all
Reply to author
Forward
0 new messages