Atcoder ABC235 D - Multiply and Rotate

[ABC235D] Multiply and Rotate

题面翻译

给定两个整数\(a\),\(x\)\(N\),你可以对这两个数进行以下操作。

  • \(x\)乘以\(a\)

  • \(x\)末尾的数字移动到\(x\)的开头(该操作只能在\(x≥10\)\(x\)不能被\(10\)整除时进行)

例如,当\(a = 2, x = 123\)时,你可以进行以下操作。

  • \(x\)乘以\(a\),使\(x\)变为\(246\)

  • \(x\)末尾的数字移动到\(x\)的开头,使\(x\)变为\(312\)

\(x\)的初始值为1,你需要用最少的操作次数使\(a\)变为\(N\)。输出最少的操作次数,如果无解,请输出\(-1\)

样例 #1

样例输入 #1

3 72

样例输出 #1

4

样例 #2

样例输入 #2

2 5

样例输出 #2

-1

样例 #3

样例输入 #3

2 611

样例输出 #3

12

样例 #4

样例输入 #4

2 767090

样例输出 #4

111

思路

这是一个bfs经典题目,代码甚至可以当成授课模版。

每次判断\(x×a\)置换操作是否合法,将结果加入队列中,并更新vector。最终输出vector中下标为\(n\)的数据。

代码实现

#include<bits/stdc++.h>
using namespace std;
vector<int> b(1e6,-1);
queue<int> q;
int main()
{
	ios::sync_with_stdio(false);
	int a,n;
	cin>>a>>n;
	
	//初始化bfs 
	b[1]=0;
	q.push(1);
	while(!q.empty())
	{
		int x=q.front();
		q.pop();
		
		//x*a
		if(1LL*a*x<=1e6&&b[x*a]==-1)
		{
			b[x*a]=b[x]+1;
			q.push(x*a);
		}
		
		//置换 
		if(x>=10&&x%10!=0)
		{
			//实现置换 
			int i=1;
			while(i<=x)
			{
				i*=10;
			}
			int y=(x%10*i+x)/10;
			if(b[y]==-1)
			{
				b[y]=b[x]+1;
				q.push(y); 
			}
		}
	}
	cout<<b[n]<<endl;
	return 0;
}

posted @ 2023-12-02 17:15  j1hx  阅读(59)  评论(0)    收藏  举报