ARC084D Small Multiple

本文介绍了一道AtCoder上的有趣题目,目标是找到使任意正整数变成N的倍数所需的最小操作数。通过巧妙转换问题视角,将操作分为加1不进位和乘10两种,利用01BFS算法优化搜索策略,最终实现O(n)的时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem

Atcoder

Solution

一道思路很巧妙的题目。
在这个题目中,我们可以把题目转化一下,对于x,若+1不进位,那么可以用1的代价使它变为x+1,然后可以花费0的代价,使它变为x*10。那么我们怎么处理使得它是n的倍数的问题呢?把所有数字转化为模n下的值即可。由于边权为0或1,用01BFS可把时间复杂度优化至 O ( n ) O(n) O(n)

Code

#include <cstring>
#include <cstdio>
#include <queue>
#define rg register
#define mk(x,y) make_pair(x,y)
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int maxn=100010;
template <typename Tp> inline int getmin(Tp &x,Tp y){return y<x?x=y,1:0;}
template <typename Tp> inline int getmax(Tp &x,Tp y){return y>x?x=y,1:0;}
template <typename Tp> inline void read(Tp &x)
{
	x=0;int f=0;char ch=getchar();
	while(ch!='-'&&(ch<'0'||ch>'9')) ch=getchar();
	if(ch=='-') f=1,ch=getchar();
	while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
	if(f) x=-x;
}
int n,dis[maxn];
pii x;
deque<pii> q;
inline int nxt(int x){return x==n-1?0:x+1;}
int main()
{
	read(n);
	memset(dis,0x3f,sizeof(dis));
	q.push_back(mk(1,1));
	while(1)
	{
		x=q.front();q.pop_front();
		if(!getmin(dis[x.first],x.second)) continue;
		if(x.first==0) break;
		if(x.first%10!=9) q.push_back(mk(nxt(x.first),x.second+1));
		q.push_front(mk(x.first*10%n,x.second));
	}
	printf("%d\n",dis[0]);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值