题解:P11825 [TOIP2024] 6174

· · 题解

题目传送门

\texttt{Solution}

实际上就是按照题意模拟,但是细节有点多。因为数据范围达到了 10^{10},正常的数组根本存不下,所以我们用哈希表存储是否进入循环。

还要注意当数字不满 d 位的时候需要补充前导零,否则会 WA(答案错误)或者是 TLE(死循环)。

\texttt{Code}

#include<bits/stdc++.h>
#define int long long
using namespace std;

unordered_map<int, bool> mp;

signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);

    int T, d;
    cin >> T >> d;

    while (T--) {
        int n;
        cin >> n;
        mp.clear();
        mp[n] = 1;

        while (true) {
            string s = to_string(n);
            while (s.size() < d) s = '0' + s;
            sort(s.begin(), s.end());
            string s1 = s;
            reverse(s1.begin(), s1.end());
            int num1 = stoll(s), num2 = stoll(s1);
            int Next = num2 - num1;
            string s2 = to_string(Next);
            while (s2.size() < d) s2 = '0' + s2;
            Next = stoll(s2);

            if (mp.count(Next) && Next != 0) {
                cout << Next << "\n";
                break;
            }
            n = Next;
            mp[Next] = 1;
        }
    }

    return 0;
}

注意这一份代码不可使用 C++98 提交,因为有很多函数和 STL 在 C++98 中没有。完结。