def isEmpty
= items.
isEmpty case n
=> items.
updated(item, n -
1) })
}
def apply
[E
](items
: Traversable
[E
]): Bag
[E
] = { val itemCounts
= mutable.
HashMap.
empty[E, Int
].
withDefaultValue(0) items.foreach(itemCounts(_) += 1)
}
}
type Solution
= Option
[Seq
[(String, String
)]]
def solve
(items
: Bag
[String
], anagrams
: String, matches
: Solution
= None
): Solution
= if (items.
isEmpty) matches
item <- items.view
(label, rest) = anagrams.splitAt(item.length)
newMatches = Option(matches.getOrElse(immutable.Queue.empty) :+ (item, label))
solution <- solve(items - item, rest, newMatches)
} yield solution
).
headOption
val items
= readLine
().
split(" ") val anagrams
= readLine
()
val sortedItems
= mutable.
Buffer.
empty[String
] val itemOrderRestorator
= mutable.
Map.
empty[String, mutable.
Queue[String
]]
sortedItems += sorted
itemOrderRestorator.
getOrElseUpdate(sorted,
new mutable.
Queue).
enqueue(item
) }
solve
(Bag
(sortedItems
), anagrams
).
map(_.
unzip) match { case None
=> println
("Ne fart") case Some
((items, labels
)) => println(labels.mkString(" "))
items.foreach(s => print(itemOrderRestorator(s).dequeue() + " "))
}
}
aW1wb3J0IHNjYWxhLmNvbGxlY3Rpb24uXwoKY2xhc3MgQmFnW0VdIHByaXZhdGUgKHZhbCBpdGVtczogTWFwW0UsIEludF0pIHsKICBkZWYgaXNFbXB0eSA9IGl0ZW1zLmlzRW1wdHkKICBkZWYgdmlldyA9IGl0ZW1zLmtleXMKICBkZWYgLShpdGVtOiBFKSA9IG5ldyBCYWdbRV0oaXRlbXMoaXRlbSkgbWF0Y2ggewogICAgY2FzZSAxID0+IGl0ZW1zIC0gaXRlbQogICAgY2FzZSBuID0+IGl0ZW1zLnVwZGF0ZWQoaXRlbSwgbiAtIDEpCiAgfSkKfQoKb2JqZWN0IEJhZyB7CiAgZGVmIGFwcGx5W0VdKGl0ZW1zOiBUcmF2ZXJzYWJsZVtFXSk6IEJhZ1tFXSA9IHsKICAgIHZhbCBpdGVtQ291bnRzID0gbXV0YWJsZS5IYXNo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