输入是:第一行 - 数组的数量(k);每下一行 - 第一个数字是数组大小,下一个数字是元素。
最大 k 为 1024。最大数组大小为 10*k。0 到 100 之间的所有数字。内存限制 - 10MB,时间限制 - 1 秒。推荐的复杂度为 k ⋅ log(k) ⋅ n,其中 n 是数组长度。
示例输入:
4
6 2 26 64 88 96 96
4 8 20 65 86
7 1 4 16 42 58 61 69
1 84
示例输出:
1 2 4 8 16 20 26 42 58 61 64 65 69 84 86 88 96 96
我有 4 个解决方案。一种使用 heapq 并逐块读取输入行,一种使用 heapq,一种使用 Counter,一种什么都不使用。
这个使用 heapq (有利于时间,但不利于内存,我认为堆是正确的方式,但是如果我将逐行读取,也许可以对其进行优化,这样我就不需要整个输入的内存):
from heapq import merge
if __name__ == '__main__':
print(*merge(*[[int(el) for el in input().split(' ')[1:]] for _ in range(int(input()))]), sep=' ')
这个是前一个的高级版本。它逐块读取行,但是它是非常复杂的解决方案,我不知道如何优化这些读取:
from heapq import merge
from functools import reduce
def read_block(n, fd, cursors, offset, has_unused_items):
MEMORY_LIMIT = 10240000
block_size = MEMORY_LIMIT / n
result = []
for i in range(n):
if has_unused_items[i]:
if i == 0:
fd.seek(cursors[i] + offset)
else:
fd.read(cursors[i])
block = ''
c = 0
char = ''
while c < block_size or char != ' ':
if cursors[i] == 0:
while char != ' ':
char = fd.read(1)
cursors[i] += 1
char = fd.read(1)
if char != '\n':
block += char
cursors[i] += 1
c += 1
else:
has_unused_items[i] = False
break
result.append([int(i) for i in block.split(' ')])
while char != '\n':
char = fd.read(1)
return result
def to_output(fd, iter):
fd.write(' '.join([str(el) for el in iter]))
if __name__ == '__main__':
with open('input.txt') as fd_input:
with open('output.txt', 'w') as fd_output:
n = int(fd_input.readline())
offset = fd_input.tell()
cursors = [0] * n
has_unused_items = [True] * n
result = []
while reduce(lambda x, p: x or p, has_unused_items):
result = merge(
result,
*read_block(n, fd_input, cursors, offset, has_unused_items)
)
to_output(fd_output, result)
这个有利于记忆(使用计数器排序,但我没有使用所有数组都排序的信息):
from collections import Counter
def solution():
A = Counter()
for _ in range(int(input())):
A.update(input().split(' ')[1:])
for k in sorted([int(el) for el in A]):
for _ in range(A[str(k)]):
yield k
这对时间有好处(但可能还不够好):
def solution():
A = tuple(tuple(int(el) for el in input().split(' ')[1:]) for _ in range(int(input())) # input data
c = [0] * len(A) # cursors for each array
for i in range(101):
for j, a in enumerate(A):
for item in a[c[j]:]:
if item == i:
yield i
c[j] += 1
else:
break
完美,如果我在第一个示例中按部分排列数组,那么我不需要整个输入的内存,但我不知道如何正确地逐块读取行。
您能否提出一些解决问题的建议?