P13159 非降序数 题解

· · 题解

:::info[形式化题意]{open} 求最大的不超过 N 的从最高位到最低位的数字是非降序的数。 :::

题目分析

贪心。

令 N 是一个字符串。

以下的 N 都被当作字符串处理。

当 N_i>N_{i+1} 时,必须使得 N_i\le N_{i+1}。(0\le i<|N|-1)

又 $\because$ 必须使得 $N_i\le N_{i+1}(0\le i<|N|-1)$, $\therefore$ 新的 $N_i\le$ 原来的 $N_i$ 且 $N_{i+1}$ 要尽量大 $(0\le i<|N|-1)$。 $\therefore$ 新的 $N_i=$ 原来的 $N_i-1$,$N_{i+1}=9(0\le i<|N|-1)$。 又 $\because$ 新的 $N_i$ 可能会影响 $N_{i-1}(1\le i<|N|-1)$, $\therefore$ 逆序处理 $N$。 $\because N$ 是字符串, $\therefore$ 需要用高精度。 $\because$ 我们想要争取不 TLE, $\therefore$ 记录所有处理过的 $N_{i+1}=9$ 的 $i_{\min}$ 为 $f$,最后统一输出。 :::info[核心代码] ```cpp lines=5,8 cin >> N; f = N.size() - 1, k = 0; for (ll i = f; i >= 1; i--) if (N[i - 1] > N[i]){ f = i, N[i--] = '9', N[i]--; while (N[i] < '0' && i >= 0) N[i--] = '9', N[i]--; i++; }while (N[k] == '0' && k <= f) k++; cout << N.substr(k, f + 1 - k) << string(N.size() - 1 - f, '9') << '\n'; ``` :::