[ABC077D] Small Multiple 题解
Prophesy_One
·
·
个人记录
题意:
定义 f(x) 表示 x 各数位之和,求 \min_{n|x}f(x)。
### 思路:
设 $dp_i=\min_{x \equiv i(\bmod n)}$,考虑在一个数 $x$ 后加一位 $y$,数变为 $10x+y$,所以有 $dp_{(10i+j)\%n}=dp_i+j$,跑最短路即可。
### 代码:
```cpp
#include<cstdio>
#include<queue>
using namespace std;
const int N=1e5+5;
const int M=1e6+5;
const int inf=1<<30;
struct edge
{
int next,to,w;
}e[M];
struct node
{
int u,d;
friend bool operator < (node x,node y)
{
return x.d>y.d;
}
};
priority_queue<node> q;
bool vis[N];
int n,cnt,in[N],dis[N];
int read()
{
int res,f=1;
char ch;
while((ch=getchar())<'0'||ch>'9')
if(ch=='-')
f=-1;
res=ch^48;
while((ch=getchar())>='0'&&ch<='9')
res=(res<<1)+(res<<3)+(ch^48);
return res*f;
}
void add(int x,int y,int z)
{
e[++cnt].next=in[x];
e[cnt].to=y;
e[cnt].w=z;
in[x]=cnt;
}
void dijkstra()
{
int i,u,v;
for(i=0;i<=n-1;i++)
dis[i]=inf;
q.push((node){n,0});
while(q.size())
{
node tmp=q.top();q.pop();
u=tmp.u;
if(vis[u])
continue;
vis[u]=1;
for(i=in[u];i;i=e[i].next)
{
v=e[i].to;
if(dis[u]+e[i].w<dis[v])
{
dis[v]=dis[u]+e[i].w;
q.push((node){v,dis[v]});
}
}
}
}
int main()
{
int i,j;
n=read();
for(i=0;i<=n-1;i++)
for(j=0;j<=9;j++)
add(i,(i*10+j)%n,j);
for(i=1;i<=9;i++)
add(n,i%n,i);
dijkstra();
printf("%d",dis[0]);
return 0;
}
```