Codeforce 1251C. Minimize The Integer

2020-10-28 11:43:51 浏览数 (2)

C. Minimize The Integer time limit per test2 seconds memory limit per test256 megabytes inputstandard input outputstandard output 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.

Example inputCopy 3 0709 1337 246432 outputCopy 0079 1337 234642 Note In the first test case, you can perform the following sequence of operations (the pair of swapped digits is highlighted): 070–––9→0079.

In the second test case, the initial integer is optimal.

In the third test case you can perform the following sequence of operations: 24643–––2→2463–––42→243–––642→234642. 因为只能交换奇数偶数,所以奇数偶数相对位置不变。然后将奇偶数分成两个队列,比较大小输出完事了!

代码语言:javascript复制
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
const int maxn=300010;
typedef long long ll;
vector<int>v1,v2;
 
int t;
char s[maxn];
int main()
{
    scanf("%d",&t);
    while(t--){
            v1.clear();
            v2.clear();
        scanf("%s",s);
        int len=strlen(s);
        int x;
        for(int i=0;i<len;i  ){
            x=s[i]-'0';
            if(x%2)v1.push_back(x);
            else v2.push_back(x);
        }
        int i,j;
        for( i=0,j=0;i<v1.size()&&j<v2.size();){
            if(v1[i]<v2[j]) cout<<v1[i],i  ;
            else cout<<v2[j],j  ;
        }
        if(i<v1.size()) for(int k=i;k<v1.size();k  )cout<<v1[k];
         if(j<v2.size()) for(int k=j;k<v2.size();k  )cout<<v2[k];
         cout<<endl;
    }
    }

0 人点赞