UVA-11549 Calculator Conundrum

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 < 10 n ) 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判圈算法,节省了set的空间开销

#include <cstdio>
#include <algorithm>
#include <iostream>

using namespace std;

int n;

int next(long long x) {
    int y = 0;
    x *= x;
    for (long long t = x; t; t /= 10, ++y);
    if (n < y)
        for (int i = 0; i < y - n; ++i) x /= 10;
    return x;
}

int main() {
    int T, k;
    cin >> T;
    while (T--) {
        cin >> n >> k;//注意题给的条件,n,k的关系
        int t1, t2, m;
        t1 = t2 = m = k;
        do {
            t1 = next(t1);
            t2 = next(t2);
            m = max(m, t2);
            t2 = next(t2);
            m = max(m, t2);
        } while (t1 != t2);
        cout << m << endl;
    }
}
原文地址:https://www.cnblogs.com/wangsong/p/7629015.html