跳到正文

个人记录

[ABC077D] Small Multiple 题解

Prophesy_One约 3 分钟
原文
文章信息与版本

文章信息

发布
2023年12月20日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 3 分钟

版本

  1. v1当前

题意:

定义 f(x)f(x) 表示 xx 各数位之和,求 min⁡n∣xf(x)\min_{n|x}f(x)。

n≤105n \leq 10^5。

思路:

设 dpi=min⁡x≡i( mod n)dp_i=\min_{x \equiv i(\bmod n)},考虑在一个数 xx 后加一位 yy,数变为 10x+y10x+y,所以有 dp(10i+j)%n=dpi+jdp_{(10i+j)\%n}=dp_i+j,跑最短路即可。

代码:

C++
#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;
}
原文