Minimize The Integer
You are given a huge integer a consisting of n digits (n is between 1 and 3⋅105, inclusive). It may contain leading zeros.
You can swap two digits on adjacent (neighboring) positions if the swapping digits are of different parity (that is, they have different remainders when divided by 2).
For example, if a=032867235 you can get the following integers in a single operation:
302867235 if you swap the first and the second digits;
023867235 if you swap the second and the third digits;
032876235 if you swap the fifth and the sixth digits;
032862735 if you swap the sixth and the seventh digits;
032867325 if you swap the seventh and the eighth digits.
Note, that you can’t swap digits on positions 2 and 4 because the positions are not adjacent. Also, you can’t swap digits on positions 3 and 4 because the digits have the same parity.
You can perform any number (possibly, zero) of such operations.
Find the minimum integer you can obtain.
Note that the resulting integer also may contain leading zeros.
Input
The first line contains one integer t (1≤t≤104) — the number of test cases in the input.
The only line of each test case contains the integer a, its length n is between 1 and 3⋅105, inclusive.
It is guaranteed that the sum of all values n does not exceed 3⋅105.
Output
For each test case print line — the minimum integer you can obtain.
题目大意:给你一个字符串,由0-9的字符组成,你可以交换相邻的两个字符,这两个字符代表的数字要满足一奇一偶,求交换后字典序最小的字符串,可以无限次交换;
思维+模拟题;
开两个队列,一个队列装奇数,一个装偶数,代表的是第 i 个位置前连续的奇数或偶数;
当第 i 个字符为奇数时,遍历装偶数的队列,直到大于第 i 个字符,手动模拟即可;
感觉还是比较难想的;
代码:
#include<bits/stdc++.h>
#define LL long long
#define pa pair<int,int>
#define ls k<<1
#define rs k<<1|1
#define inf 0x3f3f3f3f
using namespace std;
const int N=300100;
const int M=2000000;
const LL mod=1e9+7;
vector<int>ans;
queue<int>qu1,qu2;
int main(){
int t;cin>>t;
while(t--){
ans.clear();
string s;cin>>s;
for(int i=0;i<s.length();i++){
int t=s[i]-'0';
if(t&1){
int ok=1;
while(!qu2.empty()){
if(qu2.front()>t){
ok=0;
ans.push_back(t);
break;
}
ans.push_back(qu2.front());
qu2.pop();
}
if(ok) qu1.push(t);
}
else{
int ok=1;
while(!qu1.empty()){
if(qu1.front()>t){
ok=0;
ans.push_back(t);
break;
}
ans.push_back(qu1.front());
qu1.pop();
}
if(ok) qu2.push(t);
}
}
while(!qu1.empty()||!qu2.empty()){
if(!qu1.empty()) ans.push_back(qu1.front()),qu1.pop();
if(!qu2.empty()) ans.push_back(qu2.front()),qu2.pop();
}
for(int i=0;i<ans.size();i++) cout<<ans[i];
cout<<endl;
}
return 0;
}