ARC084D Small Multiple

版权声明:写得不好,转载请通知一声,还请注明出处,感激不尽 https://blog.csdn.net/As_A_Kid/article/details/82838930

Problem

Atcoder

Solution

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

猜你喜欢

转载自blog.csdn.net/As_A_Kid/article/details/82838930