Not So Distant Strings
Time limit1sMemory limit1024 MB
Given a digit string s and k, output the k-th length-n digit string when all strings are sorted by digit distance to s, then lexicographically.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Combinatorics, Greedy, Binary search
- Solved
- No attempts yet
Problem
Today in the string theory lecture, Professor Morris taught the students several ways to measure the distance between two strings. One of them works as follows. Let and be two strings of length made only of decimal digits. Professor Morris calls the digit distance between them the sum of absolute differences of the digits at equal positions, that is , where is the digit at position in and is the digit at position in .
For homework, the professor gave each student a string of length and asked them to write out all strings of length (there are of them) in non-decreasing order of digit distance to that string. When two strings have the same distance, they are compared lexicographically.
The professor has little time to check each student's work, so he also gave each student a number and asks only for the string in the -th place of the list. The students do not want to do this long and tedious task by hand, so they asked you to write a program that outputs the answer for a given string and number .
Input
The first line contains two integers and (, ), the length of the string given by the professor and the position in the final sequence that the professor is interested in.
The second line contains the string of decimal digits.
Output
Print the string of decimal digits that is written in the -th place of the sequence.
Hint
In the second example, the first seven words of the list are 00000, 00001, 00010, 00100, 01000, 10000, and 00002.
A word is not greater than a word in lexicographic order if one of the following two conditions holds:
- and , so the first word is a prefix of the second.
- There is a position such that and . In other words, at the first position where the words differ, the letter in the first word is smaller.