Melody
Time limit1sMemory limit128 MB
Given N notes with S-digit codes and a target tune of length L, choose a sequence of notes with adjacent Hamming distance at most G that minimizes total mismatch with the written tune, then output the smallest such sequence lexicographically.
- Level
Medium6 of 10
- Topics
- Dynamic programming, String, Graph
- Solved
- No attempts yet
Problem
Linas plays a peculiar wind instrument. It has holes, and Linas can play different notes (numbered from to ). Each note is produced by covering all holes in one specific way, described by a sequence of digits: the -th digit tells how the -th hole must be covered, using one of coverings labelled to . If the holes are covered in a way that matches no note, the instrument makes an unpleasant noise, so Linas always covers the holes for some valid note.
Linas wants to play a tune: a sequence of notes. However, he is not perfect. He can move from one note to the next only if the second note differs from the first in at most holes (that is, their digit sequences differ in at most positions). Because of this he sometimes has to play a note different from the one written in the tune. Every position where the note he plays differs from the written note is called a mistake.
Given the written tune, choose which notes Linas should actually play so that the number of mistakes is as small as possible, while every two consecutive played notes differ in at most holes.
Input
The first line contains three integers , , and (, ): the number of notes, the number of holes, and how many holes Linas may change between consecutive notes.
Each of the next lines contains one note as digits with no spaces; the -th digit is the covering of the -th hole for that note (each digit is between and ). No two notes are identical.
The next line contains one integer (): the length of the tune.
The last line contains integers between and , separated by single spaces: the notes of the written tune, in order.
Output
Print two lines.
The first line contains one non-negative integer: the minimum possible number of mistakes.
The second line contains integers separated by single spaces: the notes Linas should actually play. They must form a valid tune (every two consecutive notes differ in at most holes) that attains this minimum number of mistakes. If several such tunes exist, print the lexicographically smallest one, comparing the tunes as their sequences of note numbers.