C. Minimize The Integer(Educational Codeforces Round 75 (Rated for Div. 2))
time limit per test:2 seconds
memory limit per test:256 megabytes
input:standard input
output:standard output
Description
You are given a huge integer consisting of digits ( is between and , 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 ).
For example, if you can get the following integers in a single operation:
- if you swap the first and the second digits;
- if you swap the second and the third digits;
- if you swap the fifth and the sixth digits;
- if you swap the sixth and the seventh digits;
- if you swap the seventh and the eighth digits.
Note, that you can’t swap digits on positions and because the positions are not adjacent. Also, you can’t swap digits on positions and 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 — the number of test cases in the input.
The only line of each test case contains the integer a, its length n is between and , 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.
input
3
0709
1337
246432
output
0079
1337
234642
Note
In the first test case, you can perform the following sequence of operations (the pair of swapped digits is highlighted): .
In the second test case, the initial integer is optimal.
In the third test case you can perform the following sequence of operations: .
题解
我就纳闷为什么当时不会写。。。
一个奇数如果旁边有偶数的话,它就可以和旁边的偶数换位置,偶数亦然,那么如果一个队列里只有一个奇数,剩下的全是偶数的话奇数就可以出现在任何它想去的位置。也就是说奇数和偶数之间的相对位置是可以随意设置的,但是奇数不能和奇数换位置,那么奇数之间的相对位置就是固定的,偶数亦然。
那么把序列里的奇数和偶数分离开,然后把两个序列按字典序最小合并到一个序列里就是答案了。
代码
#include <iostream>
#include <algorithm>
#include <vector>
#define maxn 300005
#define _for(i, a) for(int i = 0; i < (a); i++)
using namespace std;
const int inf = 0x3f3f3f3f;
const double eps = 1e-8;
char a[maxn];
vector<int>b[2];
char ans[maxn * 2];
int al;
void init() {
_for(i, 2) b[i].clear();
al = 0;
}
int main() {
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
//freopen("in.txt", "r", stdin);
int n;
cin >> n;
_for(q, n) {
init();
cin >> a;
for (int i = 0; a[i]; i++) {
int x = a[i] - '0';
b[x % 2].push_back(x);
}
vector<int>::iterator i = b[0].begin(), j = b[1].begin();
while (i != b[0].end() || j != b[1].end()) {
int tem = inf, f = -1;
if (i != b[0].end() && *i < tem) tem = *i, f = 0;
if (j != b[1].end() && *j < tem) tem = *j, f = 1;
ans[al++] = tem + '0';
(f ? j : i)++;
}
ans[al++] = '\0';
cout << ans << "\n";
}
return 0;
}
/*
*/