Problem:
Score : 700 points

Problem Statement

Find the smallest possible sum of the digits in the decimal notation of a positive multiple of K.

Constraints

2 \leq K \leq 10^5

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print the smallest possible sum of the digits in the decimal notation of a positive multiple of K.

Sample Input 1

6

Sample Output 1

3

12=6×2 yields the smallest sum.

Sample Input 2

41

Sample Output 2

5

11111=41×271 yields the smallest sum.

Sample Input 3

79992

Sample Output 3

36

Solution in Go (1.6) (judge verdict: Accepted)

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func getScanner(fp *os.File) *bufio.Scanner {
	scanner := bufio.NewScanner(fp)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 500001), 500000)
	return scanner
}

func getNextString(scanner *bufio.Scanner) string {
	scanner.Scan()
	return scanner.Text()
}

func getNextInt(scanner *bufio.Scanner) int {
	i, _ := strconv.Atoi(getNextString(scanner))
	return i
}

func getNextInt64(scanner *bufio.Scanner) int64 {
	i, _ := strconv.ParseInt(getNextString(scanner), 10, 64)
	return i
}

func main() {
	fp := os.Stdin
	if len(os.Args) > 1 {
		fp, _ = os.Open(os.Args[1])
	}

	scanner := getScanner(fp)
	writer := bufio.NewWriter(os.Stdout)

	k := getNextInt(scanner)
	ans := solve(k)
	fmt.Fprintln(writer, ans)

	writer.Flush()
}

func solve(k int) int {
	visited := make([]int, k)
	queue := make([][2]int, k*2)
	l := k
	r := l + 1
	queue[l] = [2]int{
		1, 1,
	}
	visited[1] = 1
	for l != r {
		p := queue[l]
		l = (l + 1 + k*2) % (k * 2)
		if p[0] == 0 {
			return p[1]
		}
		visited[p[0]] = 1

		to := (p[0] * 10) % k
		if visited[to] == 0 {
			l = (l - 1 + k*2) % (k * 2)
			queue[l] = [2]int{
				to,
				p[1],
			}
		}
		to = (p[0] + 1) % k
		if visited[to] == 0 {
			queue[r] = [2]int{
				to,
				p[1] + 1,
			}
			r = (r + 1 + k*2) % (k * 2)
		}
	}

	return 0
}