As an improvement to this algorithm and to increase speed: don't just directly emit the scores. Score top K per topic in a priority queue, and then emit altogether in the cleanup method.