跳到正文

题解

题解:P11825 [TOIP2024] 6174

AFO_Lzx约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年3月1日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 2 分钟
题目
P11825

版本

  1. v2当前
  2. v1

题目传送门

Solution\texttt{Solution}

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

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

Code\texttt{Code}

C++
#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 中没有。完结。

原文