UVA11549 Calculator Conundrum

Calculator Conundrum

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

 

不难发现答案会出现循环,相当于在一个有限状态自动机上求环,使用floyd判圈法即可

如何证明一定能走完整个环,以及复杂度如何?

设环长为L,走了x步,则

x mod L = 2x mod L

即2x = x mod L

也就是x = 0 mod L

x最小为L

也就是一定在L步相遇,且L步前不相遇

这样走一步的那个人一定能走过整个环

复杂度O(L)

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <cstdlib>
 5 #include <algorithm>
 6 #include <queue>
 7 #include <vector>
 8 #define min(a, b) ((a) < (b) ? (a) : (b))
 9 #define max(a, b) ((a) > (b) ? (a) : (b))
10 #define abs(a) ((a) < 0 ? (-1 * (a)) : (a))
11 inline void swap(long long &a, long long &b)
12 {
13     long long tmp = a;a = b;b = tmp;
14 }
15 inline void read(long long &x)
16 {
17     x = 0;char ch = getchar(), c = ch;
18     while(ch < '0' || ch > '9') c = ch, ch = getchar();
19     while(ch <= '9' && ch >= '0') x = x * 10 + ch - '0', ch = getchar();
20     if(c == '-') x = -x;
21 }
22 
23 const long long INF = 0x3f3f3f3f;
24 
25 long long t, ma, ans;
26 
27 long long run(long long a)
28 {
29     a *= a;
30     while(a >= ma) 
31         a /= 10;
32     return a;
33 }
34 
35 int main()
36 {
37     read(t);
38     for(;t;--t)
39     {
40         long long k,n;read(k), read(n);
41         ma = 1;
42         for(register long long i = 1;i <= k;++ i)  ma *= 10;
43         long long k1 = n, k2 = n;
44         ans = n;
45         do
46         {
47             k1 = run(k1), k2 = run(k2), ans = max(ans, k1);
48             k1 = run(k1), ans = max(ans, k1);
49         }while(k1 != k2);
50         printf("%lld\n", ans);
51     }
52     return 0;
53 } 
UVA11549

 

转载于:https://www.cnblogs.com/huibixiaoxing/p/8287259.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值