Comment detail

情報オリンピック2006年度国内本選問題1 (Nested Flatten)

k個の範囲の先頭と末尾でそれぞれファイルポインタを持って加算・減算していく方法も思いついたのですが、十万くらいのサイズならいいかと、インメモリで配列を確保しました。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import sys

def main():
    io = open("input.txt")
    n, k = [int(s) for s in io.next().split()]
    if not(1 <= k <= n):
        raise ValueError("invalid k, n")
    a = [int(io.next().strip()) for _ in xrange(n)]
    result = current = sum(a[i] for i in xrange(k))
    for i in xrange(n - k):
        current -= a[i]
        current += a[i + k]
        result = max(result, current)
    open("output.txt", "w").write("%d\n" % result)

if __name__ == '__main__':
    main()

なんとなくwith文。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
--- a.py        Thu Jan 31 09:14:57 2008
+++ b.py        Thu Jan 31 09:12:23 2008
@@ -1,18 +1,20 @@

+from __future__ import with_statement
 import sys

 def main():
-       io = open("input.txt")
-       n, k = [int(s) for s in io.next().split()]
-       if not(1 <= k <= n):
-               raise ValueError("invalid k, n")
-       a = [int(io.next().strip()) for _ in xrange(n)]
+       with open("input.txt") as io:
+               n, k = [int(s) for s in io.next().split()]
+               if not(1 <= k <= n):
+                       raise ValueError("invalid k, n")
+               a = [int(io.next().strip()) for _ in xrange(n)]
        result = current = sum(a[i] for i in xrange(k))
        for i in xrange(n - k):
                current -= a[i]
                current += a[i + k]
                result = max(result, current)
-       open("output.txt", "w").write("%d\n" % result)
+       with open("output.txt", "w") as io:
+               print >>io, result

 if __name__ == '__main__':
        main()

Index

Feed

Other

Link

Pathtraq

loading...