#!/usr/bin/python3
import sys
def diff_weight(pattern, line, weight):
source = list(line)
count = 0
for s in pattern:
try:
source.remove(s)
except ValueError:
count += 1
if count > weight:
return False
if len(source) + count > weight:
return False
return True
weight = int(sys.argv[1])
try:
with open(sys.argv[2]) as file:
lines = file.readlines()
except IndexError:
lines = sys.stdin.readlines()
while lines:
pattern = lines.pop()
print(pattern, end="")
for i in range(len(lines)-1, -1, -1):
if diff_weight(pattern, lines[i], weight):
print(lines[i], end="")
lines.pop(i)