抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

巧妙啊!

不妨考虑枚举答案,我们不要从小到大枚举,而是从位数之和从小到大枚举。

考虑一个数xxx+1x+1xx的数位之和+1+1x×10x \times 10数位和不变。

于是我们可以在modk\bmod k的意义下计算xx,将x,x+1x,x+1连一条长度为11的边,将x,x×10x,x\times 10连一条长度为00的边。

于是答案就是101 \to 0的距离。

具体实现时使用一种神奇的bfs\rm bfs,具体看代码吧。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <bits/stdc++.h>
#define MAXN 100005
using namespace std;
inline int read(){
int x=0,f=1;
char ch=getchar();
while (ch<'0'||ch>'9'){
if (ch=='-') f=-1;
ch=getchar();
}
while (ch>='0'&&ch<='9'){
x=(x<<1)+(x<<3)+(ch^'0');
ch=getchar();
}
return x*f;
}
int d[MAXN],vis[MAXN];
deque<int>Q;
inline void Push(int x,int pre,int len,bool flag){
d[x]=min(d[x],d[pre]+len);
if (flag) Q.push_front(x);
else Q.push_back(x);
}
int main(){
int K=read();
memset(d,0x3f,sizeof(d));
Q.push_front(1),d[1]=1;
while (Q.size()){
int x=Q.front();Q.pop_front();
if (!vis[x]) vis[x]=true;
else continue;
if (!x){
printf("%d\n",d[x]);
return 0;
}
Push((x+1)%K,x,1,0);
Push((x*10)%K,x,0,1);
}
}

评论