题解:P11825 [TOIP2024] 6174

· · 题解

题目传送门

解题思路

我们可以建立一个桶,存放你的数有没出现。如果我们减出来的数你出现过[^1],第一个发现的即是答案,立马输出,退出循环。

当然,这个数可以达到 10 位数,如果我们用建立一个 10^{10} 的 bool 类型桶,直接就 \colorbox{#0E1D69}{\color{#ffffff}{MLE}} 了。我们需要建立 map 表示桶。

需要知道这几个函数[^2]:

  1. to_string(整数):把整数类型[^3]转换为 string 类型。
  2. stoll(str):把 string 类型转换为 long long 类型。如果要转换 int 类型,请使用 stoi(str)。

要注意

输入的数没有前导 0,需要手动补上。(WA 记录)

AC 代码^4:

#include<iostream>
#include<map>
#include<string>
#include<algorithm>
using namespace std;
map<long long,bool> t;
int main(){
    int n,d;
    cin>>n>>d;
    for(int i=1;i<=n;i++){
        t.clear();//记得清空桶哦!
        long long x;
        cin>>x;
        while(!t.count(x)){
            t[x]=1;
            string a=to_string(x);
            if(a.size()!=d){
                int cha=d-a.size();
                for(int i=1;i<=cha;i++){
                    a='0'+a;
                }
            }
            string b=a;
            sort(a.begin(),a.end(),greater<char>());
            sort(b.begin(),b.end());
            x=(stoll(a)-stoll(b));
        }
        cout<<x<<'\n';
    }
    return 0;
}

[^1]:〔如果我们减出来的数你出现过〕:比如减到了 6174,发现我的 6174 之前也被减出来过,桶里面有标记。 [^2]: 需要支持 C++11 才能使用这些函数。 [^3]:〔整数类型〕:包括 short、int、long、long long、unsigned short、unsigned int、unsigned long、unsigned long long 类型。