• 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 

    1. #include
    2. #include
    3. #include
    4. using namespace std;
    5. const int N=1e6+10;
    6. int b[N];
    7. queue<int> q;
    8. int main()
    9. {
    10. int a,n;cin>>a>>n;
    11. q.push(n);
    12. memset(b,-1,sizeof b);
    13. b[n]=0;
    14. while(q.size())
    15. {
    16. int x=q.front();q.pop();
    17. if(x<2) break;
    18. if(x%a==0&&b[x/a]==-1) b[x/a]=b[x]+1,q.push(x/a);
    19. if(x>=10)
    20. {
    21. string s=to_string(x);
    22. int y=stoi(s.substr(1)+s[0] );
    23. if(s[1]!='0'&&b[y]==-1) b[y]=b[x]+1,q.push(y);
    24. }
    25. }
    26. cout<1];
    27. return 0;
    28. }

     

  • 相关阅读:
    线程安全的随机数
    Linux: alsa-lib 插件简介
    RHCE8 资料整理(五)
    作为一面面试官,如何考察候选人
    使用并查集处理树的路径
    Linux 测试端口是否放行
    Hdu2022 多校训练(5) BBQ
    超详细的MySQL基本操作
    Vatee万腾的数字化掌舵:Vatee科技解决方案的全面引领
    编程小白如何成为大神?大学新生的最佳入门攻略
  • 原文地址:https://blog.csdn.net/m0_63363129/article/details/126078331