6616: Small Multiple
时间限制: 1 Sec 内存限制: 512 MB
提交: 408 解决: 61
[提交] [状态] [讨论版] [命题人:admin]
题目描述
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的倍数使其数位和最小,输出数位和,k<=10^5。
【算法】最短路
【题解】考虑极端情况数字是可能爆long long的(例如k*num=100...000),所以确定基本方向是依次考虑答案x的每个数位。
考虑x初始是1~9,每次在后面加一位,就有x*10+0~9十种操作。
但是x可以无限大,而且x必须是k的倍数这点很难实现,综合这两点可以考虑%k。
进一步发现,%k意义下同余的数字是等价的,也就是%k等于同一个数的x只需要保留数字和最小的。
那么就可以得到算法:
k个点表示%k=0~k-1的最小数字和,起点是1~k-1(d[i]=i),终点为0,x向(x*10+0~9)%k连边权为0~9的边,跑最短路。
#include<bits/stdc++.h>
using namespace std;
int k,cnt,a[100004];
struct edge
{
int to,ans,w;
} e[500004];
queue<int>q;
int dis[100004];
void add(int u,int v,int w)
{
e[++cnt].to = v;
e[cnt].ans = a[u];
e[cnt].w=w;
a[u]=cnt;
}
int main()
{
scanf("%d",&k);
for(int i=0; i<k; i++)
{
add(i,(i+1)%k,1);
add(i,(i*10)%k,0);
}
q.push(1);
memset(dis,100,sizeof(dis));
dis[1]=0;
while(!q.empty())
{
int x=q.front();
q.pop();
for(int i=a[x]; i; i=e[i].ans)
if( dis[e[i].to]>dis[x]+e[i].w)
{
dis[e[i].to]=dis[x]+e[i].w;
q.push(e[i].to);
}
}
printf("%d\n",dis[0]+1);
return 0;
}