Small Multiple
时间限制: 1 Sec 内存限制: 512 MB
题目描述
Find the smallest possible sum of the digits in the decimal notation of a positive multiple of K.
Constraints
2≤K≤105
K is an integer.
输入
Input is given from Standard Input in the following format:
K
输出
Print the smallest possible sum of the digits in the decimal notation of a positive multiple of K.
样例输入
6
样例输出
3
提示
12=6×2 yields the smallest sum.
题意
找一个k的倍数x,其中x各位相加最小
思路
也是看的别人的题解,确实想不到是最短路。。。。。
想一下,对于x变化的话,要么+1从0到9(变化加1),要么*10(变化加0),又因为x%k与x对k的影响是一样的,例如10%6=4,10要变成6的倍数要加2,4同样是加2;那么x%6=0;所以只要求到0的最短路就是答案。
代码
#include<bits/stdc++.h>
using namespace std;
const int inf=100000000;
struct fun{
int v;
int next;
int w;
}a[200005];
int vis[100005],cnt=0,head[100005],k,dis[100006];
void add(int u,int v,int w)
{
a[cnt].v=v;
a[cnt].w=w;
a[cnt].next=head[u];
head[u]=cnt++;
}
void spfa()
{
memset(head,-1,sizeof(head));
for(int i=0;i<k;i++)
{
add(i,(i+1)%k,1);
add(i,i*10%k,0);
vis[i]=0;
dis[i]=inf;
}
dis[1]=1;
vis[1]=1;
queue<int>q;
q.push(1);
while(!q.empty())
{
int u=q.front();
q.pop();
for(int i=head[u];i!=-1;i=a[i].next)
{
if(dis[a[i].v]>dis[u]+a[i].w)
{
dis[a[i].v]=dis[u]+a[i].w;
if(!vis[a[i].v])
{
q.push(a[i].v);
vis[a[i].v]++;
}
}
}
vis[u]=0;
}
}
int main()
{
scanf("%d",&k);
spfa();
printf("%d\n",dis[0]);
return 0;
}