E - What a Ridiculous Election
In country Light Tower, a presidential election is going on. There are two candidates, Mr. X1 and Mr. X2, and both of them are not like good persons. One is called a liar and the other is called a maniac. They tear(Chinese English word, means defame) each other on TV face to face, on newspaper, on internet . . . on all kinds of media. The country is tore into two parts because the people who support X1 are almost as many as the people who support X2. After the election day, X1 and X2 get almost the same number of votes. No one gets enough votes to win. According to the law of the country, the Great Judge must decide who will be the president. But the judge doesn’t want to offend half population of the country, so he randomly chooses a 6 years old kid Tom and authorize him to pick the president. Sounds weird? But the democracy in Light Tower is just like that. The poor or lucky little kid Tom doesn’t understand what is happening to his country. But he has his way to do his job. Tom’s ao shu(Chinese English word, means some kind of weird math for kids) teacher just left him a puzzle a few days ago, Tom decide that he who solve that puzzle in a better way will be president. The ao shu teacher’s puzzle is like this: Given a string which consists of five digits(‘0’..‘9’), like “02943”, you should change “12345” into it by as few as possible operations. There are 3 kinds of operations: 1. Swap two adjacent digits.
2. Increase a digit by one. If the result exceed 9, change it to it modulo 10.
3. Double a digit. If the result exceed 9, change it to it modulo 10.
You can use operation 2 at most three times, and use operation 3 at most twice. As a melon eater (Chinese English again, means bystander), which candidate do you support? Please help him solve the puzzle.
Input There are no more than 100,000 test cases. Each test case is a string which consists of 5 digits.
Output For each case, print the minimum number of operations must be used to change “12345” into the given string. If there is no solution, print ‘-1’.
Sample Input 12435 99999 12374
Sample Output 1 -1 3
&:先预先处理 12345 能够到达其他数的最小步数,在进行 O(1) 查询就可以了。这里的预先处理用 BFS 来进行。