Multiply and Rotate (BFS/队列)

Multiply and Rotate

时间限制: 1.000 Sec  内存限制: 128 MB

题目描述

We have a positive integer a. Additionally, there is a blackboard with a number written in base 10.
Let x be the number on the blackboard. Takahashi can do the operations below to change this number.

Erase x and write x multiplied by a, in base 10.
See x as a string and move the rightmost digit to the beginning.
This operation can only be done when x≥10 and x is not divisible by 10.
For example, when a=2,x=123, Takahashi can do one of the following.


Erase x and write x×a=123×2=246.
See x as a string and move the rightmost digit 3 of 123 to the beginning, changing the number from 123 to 312.
The number on the blackboard is initially 1. What is the minimum number of operations needed to change the number on the blackboard to N? If there is no way to change the number to N, print −1.

Constraints
2≤a<106
2≤N<106
 
All values in input are integers.

输入

输出

Print the answer.

样例输入 

【样例1】
3 72
【样例2】
2 5
【样例3】
2 611
【样例4】
2 767090

样例输出 

【样例1】
4
【样例2】
-1
【样例3】
12
【样例4】
111

提示

样例1解释
We can change the number on the blackboard from 1 to 72 in four operations, as follows.
Do the operation of the first type: 1→3.
Do the operation of the first type: 3→9.
Do the operation of the first type: 9→27.
Do the operation of the second type: 27→72.
It is impossible to reach 72 in three or fewer operations, so the answer is 4.
样例2解释
It is impossible to change the number on the blackboard to 5.
样例3解释
There is a way to change the number on the blackboard to 611 in 12 operations: 1→2→4→8→16→32→64→46→92→29→58→116→611, which is the minimum possible.

题目大意:给定两个数a,n,最初有一个数字1,问每次执行如下操作之一,最少的变为n的操作次数是多少?

1.乘以a

2.如果这个数>=0并且不是10的倍数,那么把他的最后一位移到第一位


两个字符与十进制相互转换的函数:

1.to_string(x) 将整数x转化为字符串s

2.stoi(s) 将字符串s转化为整数x 

#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int N=1e6+10;
int b[N];
queue<int> q;

int main()
{
	int a,n;cin>>a>>n;
	q.push(n);
	memset(b,-1,sizeof b);
	b[n]=0;
	
	while(q.size())
	{
		int x=q.front();q.pop();
		if(x<2) break;
		if(x%a==0&&b[x/a]==-1) b[x/a]=b[x]+1,q.push(x/a);
		if(x>=10)
		{
			string s=to_string(x);
			int y=stoi(s.substr(1)+s[0] );
			if(s[1]!='0'&&b[y]==-1) b[y]=b[x]+1,q.push(y);
		}
	}
	cout<<b[1];
	
	
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值