You have a string ss consisting of digits from 00 to 99 inclusive. You can perform the following operation any (possibly zero) number of times:
- You can choose a position ii and delete a digit dd on the ii-th position. Then insert the digit min(d+1,9)min(d+1,9) on any position (at the beginning, at the end or in between any two adjacent digits).
What is the lexicographically smallest string you can get by performing these operations?
A string aa is lexicographically smaller than a string bb of the same length if and only if the following holds:
- in the first position where aa and bb differ, the string aa has a smaller digit than the corresponding digit in bb.
Input
The first line contains a single integer tt (1≤t≤1041≤t≤104) — the number of test cases. Then the test cases follow.
Each test case consists of a single line that contains one string ss (1≤|s|≤2⋅1051≤|s|≤2⋅105) — the string consisting of digits. Please note that ss is just a string consisting of digits, so leading zeros are allowed.
It is guaranteed that the sum of lengths of ss over all test cases does not exceed 2⋅1052⋅105.
Output
Print a single string — the minimum string that is possible to obtain.
Example
input
Copy
4
04829
9
01
314752277691991
output
Copy
02599 9 01 111334567888999
Note
In the first test case:
- Delete 88 and insert 99 at the end of the notation. The resulting notation is 0429904299.
- Delete 44 and insert 55 in the 33-rd position of the notation. The resulting notation is 0259902599.
Nothing needs to be done in the second and third test cases.
题意:
给定一个只含数字的字符串,我们可以进行无数次这样的操作:
·对于一个位置的数字字符,可以将他变成min(s[i]-'0'+1,9)。求最小字典序
所以我们可以这样想,每次操作无论如何都是使数字变大或者不变,所以尽量少操作无疑是正解,但是有时候不得不操作:
对于当前数字字符,我们后面有比他小的,那么我们肯定想要把比他小的字符放到前面。
所以这时候我们就要进行操作了,把当前这个较大的字符变成min(s[i]-'0'+1,9),放到另外一个字符串中并且从当前字符串删除,最后的答案就是输入的字符串剩余的字符+sort(处理的字符)
#include<iostream>
#include<algorithm>
#include<stack>
#include<string>
using namespace std;
const int inf=2e9+10,N=2e5+10;
int n,m;
int q[N],p[N],past[N];
string s;
int main() {
int T;
cin>>T;
while(T--) {
cin>>s;
n=s.size();
for(int i=1; i<=n; i++)past[i]=0; //初始化每个字符后面是否有比他小的
s=' '+s;
int res=inf;//初始化最大值
for(int i=n; i>=1; i--) {
int num=s[i]-'0';
if(num>res)past[i]=1;//如果这个num大于past说明这个数比较大,需要进行操作
else res=s[i]-'0';
}
string ans;
for(int i=n; i>=1; i--) {
if(past[i]) {//这个数后面有比他小的,删除它并进行操作
if(s[i]-'0'<9)ans+=char(s[i]+1);
else ans+=s[i];
} else {
ans+=s[i];
}
}
sort(ans.begin(),ans.end());
cout<<ans<<endl;
}
}