• 回文数 洛谷 - P1015


    [NOIP1999 普及组] 回文数 - 洛谷

    题目大意:给出一个数n和一个100位以内的n进制数s,每步操作令s=s+s的头尾翻转,问30步操作内最少多少步能将s变成一个回文数

    2<=n<=10或n=16

    思路:因为最多只有30步,100位数,所以模拟的时间复杂度肯定够,直接上高精度非10进制加法运算模板

    1. //#include<__msvc_all_public_headers.hpp>
    2. #include
    3. using namespace std;
    4. typedef long long ll;
    5. const int N = 3e5+ 5;
    6. const ll MOD = 998244353;
    7. int n;
    8. bool check(string x)
    9. {//检查是否是回文数
    10. string y = x;
    11. reverse(y.begin(), y.end());
    12. return y == x;
    13. }
    14. void init()
    15. {
    16. }
    17. string add(string x1, string x2,int d)
    18. {//高精度d进制加法
    19. string ret;
    20. int l = x1.length();//本题中两数位数相同
    21. int pre = 0;
    22. for (int i = l - 1; i >= 0; i--)
    23. {//从后向前逐位遍历
    24. int x = x1[i] - '0' + x2[i] - '0' + pre;//当前位的和加上进位
    25. if (d == 16)
    26. {
    27. if (x1[i] >= 'A' && x1[i] <= 'F')
    28. {//16进制的字母要单独处理
    29. x -= x1[i] - '0';
    30. x += x1[i] - 'A' + 10;
    31. }
    32. if (x2[i] >= 'A' && x2[i] <= 'F')
    33. {
    34. x -= x2[i] - '0';
    35. x += x2[i] - 'A' + 10;
    36. }
    37. }
    38. pre = x / d;//进位
    39. x = x % d;//当前位的数
    40. if (d == 16)
    41. {
    42. if (x >= 10)
    43. {
    44. ret += 'A' + x - 10;
    45. continue;
    46. }
    47. }
    48. ret += '0' + x;//先放到最后一位
    49. }
    50. if (pre)
    51. {//处理最后的进位
    52. if (d == 16 && pre >= 10)
    53. {
    54. ret += 'A' + pre - 10;
    55. }
    56. else
    57. ret += '0' + pre;
    58. }
    59. reverse(ret.begin(), ret.end());//最后再把整个倒过来
    60. return ret;
    61. }
    62. void solve()
    63. {
    64. cin >> n;
    65. init();
    66. string s;
    67. cin >> s;
    68. int cnt = 0;
    69. while (cnt <= 30)
    70. {
    71. if (check(s))
    72. {
    73. cout << "STEP=" << cnt << '\n';
    74. return;
    75. }
    76. cnt++;
    77. string s2 = s;
    78. reverse(s2.begin(), s2.end());
    79. s = add(s, s2, n);
    80. //cout << s << '\n';
    81. }
    82. cout << "Impossible!";
    83. cout << '\n';
    84. }
    85. int main()
    86. {
    87. ios::sync_with_stdio(false);
    88. cin.tie(0);
    89. int t;
    90. t=1;
    91. // cin>>t;
    92. while (t--)
    93. {
    94. solve();
    95. }
    96. return 0;
    97. }

  • 相关阅读:
    【MySQL】存储引擎
    全面解析缓存应用经典问题
    【OpenCV】在MacOS上使用OpenCvSharp
    斐波那契数列|||川(马蹄集)
    Excel——对其他工作表和工作簿的引用
    AOP是什么?如何使用AOP?
    centos7 vsftp搭建ftp服务器,实现虚拟用户登录
    VSCode中ESLint插件修复+配置教程
    Hibernate EntityManager 指南
    GAN.py
  • 原文地址:https://blog.csdn.net/ashbringer233/article/details/133947692