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 C++14 (GCC 5.4.1) (judge verdict: Accepted)

#include<bits/stdc++.h>
#define fs first
#define se second
using namespace std;

typedef long long ll;
typedef pair<int,int> pii;
typedef double db;

const int maxn=5e5+5;
const ll inf=0x3f3f3f3f;
const ll mod=1e9+7;

int top = 0;
int head[maxn];

struct Edge{
	int to,w,next;
}edge[maxn*2];

void init(){
	top=0;
	memset(head,-1,sizeof(head));
}

void addedge(int u,int v,int w){
	edge[top].w=w;
	edge[top].to=v;
	edge[top].next=head[u];
	head[u]=top++;
}

struct Node{
	int id,val;
	Node(int id,int val):id(id),val(val){
	}
	bool operator <(const Node &bb) const
	{
		return val > bb.val;
	}
};

int dis[maxn];
int vis[maxn];

void dijk(int st){
	memset(dis,0x3f,sizeof(dis));
	memset(vis,0,sizeof(vis));
	priority_queue<Node> q;
	dis[st]=0;
	q.push(Node(st,0));
	while(!q.empty()){
		int u=q.top().id;
		q.pop();
		if(vis[u]) continue;
		vis[u]=1;
		for (int i = head[u]; i!=-1; i=edge[i].next)
		{
			int to=edge[i].to;int w=edge[i].w;
			if(dis[to]>dis[u]+w&&!vis[to]){
				dis[to]=dis[u]+w;
				q.push(Node(to,dis[to]));
			}
		}
	}
}

int main(){
	init();
	int k;
	scanf("%d",&k);
	for(int i=1;i<=k-1;i++){
		addedge(i,(i+1)%k,1);
		addedge(i,(i*10)%k,0);
	}
	dijk(1);
	printf("%d",dis[0]+1);
	return 0;
}