洛谷 UVA11549 Calculator Conundrum

Description

Alice got a hold of an old calculator that can display n n n digits. She was bored enough to come up with the following time waster. She enters a number k k k then repeatedly squares it until the result overflows. When the result overflows, only the n n 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 n n and k k 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 ) t (1 ≤ t ≤ 200) t(1t200), the number of test cases. Each test case contains two integers n ( 1 ≤ n ≤ 9 ) n (1 ≤ n ≤ 9) n(1n9) and k ( 0 ≤ k < 1 0 n ) k (0 ≤ k < 10^n) k(0k<10n) where n n n is the number of digits this calculator can display k k 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.

Solution

1.采用Floyd判圈法。

利用k1,k2快慢指针,k1速度为1,k2速度为2,有 1 × T = 2 × T 2 1\times T = 2\times \frac{T}{2} 1×T=2×2T 成立,当二者遍历的答案相同时,k1刚好走完一个周期。

Code

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;

#define MOD 1000000007
#define intmax 2147483647
#define memmax 0x7fffffff


inline ll read()
{
    
    
	ll x=0,f=1;char ch=getchar();
	while (ch<'0'||ch>'9'){
    
    if (ch=='-') f=-1;ch=getchar();}
	while (ch>='0'&&ch<='9'){
    
    x=x*10+ch-48;ch=getchar();}
	return x*f;
}

ll t;
ll n, k;
ll lim;

ll getNext(ll num)
{
    
    
    ll ans = num*num;
    while(ans >= lim)
        ans /= 10;

    return ans;
}

void solve()
{
    
    
    n = read(), k = read();
    lim = 1;
    for(int i=1; i<=n; i++)
        lim *= 10;

    ll k1 = k, k2 = k;
    ll ans = k;
    do
    {
    
    
        k1 = getNext(k1);
        ans = max(ans, k1);

        k2 = getNext(k2);
        ans = max(ans, k2);
        k2 = getNext(k2);
        ans = max(ans, k2);
        
    }while(k1 != k2);

    printf("%lld\n", ans);
}

int main()
{
    
    
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    
    t = read();
    while (t--)
        solve();
    
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45812280/article/details/121230550