zoukankan      html  css  js  c++  java
  • Designing Efficient Algorithms [Examples]~C

    Alice got a hold of an old calculator that can display n digits. She was bored enough to come up with the following time waster.

    She enters a number k then repeatedly squares it until the result overflows. When the result overflows, only the n most significant digits are displayed on the screen and an error flag appears. Alice can clear the error and continue squaring the displayed number. She got bored by this soon enough, but wondered:

    “Given n and k, what is the largest number I can get by wasting time in this manner?”

    Input

    The first line of the input contains an integer t (1 ≤ t ≤ 200), the number of test cases. Each test case contains two integers n (1 ≤ n ≤ 9) and k (0 ≤ k < 10n) where n is the number of digits this calculator can display k is the starting number.

    Output

    For each test case, print the maximum number that Alice can get by repeatedly squaring the starting number as described.

    Sample Input

    2

    1 6

    2 99

    Sample Output

    9

    99

    解题思路:题目意思是:有一个老式计算机,只能显示n位数字。有一天,你无聊了,于是输入一个整数k,然后反复平方,直到溢出。每次溢出时,计算机会显示出结果的最高n位和一个错误标记。然后清除标记,继续平方。如果一直这样做下去,能得到的最大数是多少?比如,当n=1,k=6时,计算机将依次显示6、3(36的最高位),9、8(81的最高位),6(64的最高位),3,..........

    程序代码:

    #include <iostream>
    #include <cstdio>
    #include <algorithm>
    #include <cmath>
    #include <set>
    using namespace std;
    
    int next(int n, int k)
    {
        long long res = (long long)k*k;
    
        while(res >= n)
            res/=10;
        return res;
    }
    
    int main()
    {
        int T;
        scanf("%d", &T);
        for(int i=0;i<(T);i++)
        {
            int n, k;
            scanf("%d%d", &n, &k);
            n = (int)pow(10.0, n);//计算10的n次幂赋值给n
            int ans = 1<<31;
            set<int> ss;
            while(1)
            {
                ans = max(ans, k);
    
                if(ss.count(k))
                    break;
                else
                    ss.insert(k);//把k放入容器
    
                k = next(n, k);
            }
    
            printf("%d
    ", ans);
        }
        return 0;
    }
    

     

  • 相关阅读:
    hdu 5036 概率+bitset
    hdu 5037 周期优化
    hdu 5038 求出现次数最多的grade
    hdu 5040 bfs
    hdu 5045 N个人做M道题的正确率
    hdu 5046 二分+DLX模板
    hdu 5047 大数找规律
    c:set注意事项
    It is indirectly referenced from required .class files(导入项目报错原因与解决方法)
    oracle-01722,函数subtr,instr
  • 原文地址:https://www.cnblogs.com/chenchunhui/p/4925056.html
Copyright © 2011-2022 走看看