Minimum Ternary String (CodeForces
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2').
You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa).
For example, for string "010210" we can perform the following moves:
- "010210" →→ "100210";
- "010210" →→ "001210";
- "010210" →→ "010120";
- "010210" →→ "010201".
Note than you cannot swap "02" →→ "20" and vice versa. You cannot perform any other operations with the given string excluding described above.
You task is to obtain the minimum possible (lexicographically) string by using these swaps arbitrary number of times (possibly, zero).
String aa is lexicographically less than string bb (if strings aa and bb have the same length) if there exists some position ii (1≤i≤|a|1≤i≤|a|, where |s||s| is the length of the string ss) such that for every j<ij<i holds aj=bjaj=bj, and ai<biai<bi.
Input
The first line of the input contains the string ss consisting only of characters '0', '1' and '2', its length is between 11 and 105105 (inclusive).
Output
Print a single string — the minimum possible (lexicographically) string you can obtain by using the swaps described above arbitrary number of times (possibly, zero).
Examples
Input
100210
Output
001120
Input
11222121
Output
11112222
Input
20
Output
20
題解:觀察交換規則我們發現,01可以交換,12可以交換,那麼1字元作為一個承上啟下的字元,他可以在整個字串中任意滑動,因此字串中的所有的1必須都連續的擺放在第一個2的前面,而第一個2前面的0毫無疑問連續的放在最前面,而第一個2後面的0,因為被2擋住,無論如何都不可能越過前面的2,故從第一個2開始後面的0和2相對順序不變,因此我們只需要統計出第一個2前面的0有多少個,所有1有多少個,第一個2的位置,輸出時,先輸出第一個2前面的所有0,再輸出所有1,然後從第一個2的位置開始往後遍歷只輸出0和2.
程式碼如下:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#include<cmath>
#include<map>
#include<stack>
#include<vector>
#include<queue>
#include<set>
#include<algorithm>
#define max(a,b) (a>b?a:b)
#define min(a,b) (a<b?a:b)
#define swap(a,b) (a=a+b,b=a-b,a=a-b)
#define maxn 320007
#define N 100000000
#define INF 0x3f3f3f3f
#define mod 1000000009
#define e 2.718281828459045
#define eps 1.0e18
#define PI acos(-1)
#define lowbit(x) (x&(-x))
#define read(x) scanf("%d",&x)
#define put(x) printf("%d\n",x)
#define memset(x,y) memset(x,y,sizeof(x))
#define Debug(x) cout<<x<<" "<<endl
#define lson i << 1,l,m
#define rson i << 1 | 1,m + 1,r
#define ll long long
//std::ios::sync_with_stdio(false);
//cin.tie(NULL);
using namespace std;
char a[1111111];
int main()
{
cin>>a;
int flag=0;
int pos;
ll num1=0;
ll num0=0;
int l=strlen(a);
for(int i=0;i<l;i++)
{
if(flag==0&&a[i]=='2')
{
flag=1;
pos=i;
}
if(a[i]=='1')
num1++;
if(flag==0&&a[i]=='0')
num0++;
}
for(int i=0;i<num0;i++)
{
cout<<"0";
}
for(int i=0;i<num1;i++)
{
cout<<"1";
}
for(int i=pos;i<l;i++)
{
if(a[i]=='1')
continue;
cout<<a[i];
}
cout<<endl;
return 0;
}