1009B Minimum Ternary String
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
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
Input100210Output
001120Input
11222121Output
11112222Input
20Output
20開始時想的過於狹隘了,區域性分析未果的情況下,沒有做到整體的去分析。對 0 1 2 的特點進行分析,1 既可以與 0 交換 ,也可以與 2 交換 ,所以說 1 可以出現在字串的任意位置,為了使字串的字典序小,1 必定要出現在 2 的前面,且要出現在第一個 2 的前面,所以 1 的位置就確定了。再看 0 2 ,因為所有的 1 已經都被抽到了第一個 2 的前面,且 2 不能借助 1 使它本身換到 0 的後面(以 2 1 0為例),所以,第一個 2 後面的序列是不變的。再看第一個 2 前面的序列,顯然,第一個 2 之前的 0 要在所有的 1 之前。分析完畢。切入點:0 1 2 的特點、字串的格式
1 #include<cstdio> 2 #include<cstdlib> 3 #include<cstring> 4 #include<string> 5 #include<cmath> 6 #include<algorithm> 7 #include<queue> 8 #include<stack> 9 #include<deque> 10 #include<map> 11 #include<iostream> 12 using namespace std; 13 typedef long long LL; 14 const double pi=acos(-1.0); 15 const double e=exp(1); 16 const int N = 100009; 17 18 char con[100009]; 19 int main() 20 { 21 int i,p,j,n,k; 22 int head,tail,a=0,b=0,flag; 23 24 scanf("%s",con); 25 k=strlen(con); 26 for(i=0;i<k;i++) 27 { 28 if(con[i]=='1') 29 a++; 30 } 31 flag=0; 32 for(i=0;i<k;i++) 33 { 34 if(con[i]=='0') 35 printf("0"); 36 else if(con[i]=='2'&&flag==0) 37 { 38 for(j=1;j<=a;j++) 39 printf("1"); 40 printf("2"); 41 flag=1; 42 } 43 else if(con[i]=='2'&&flag==1) 44 { 45 printf("2"); 46 } 47 } 48 if(flag==0) 49 { 50 for(i=1;i<=a;i++) 51 printf("1"); 52 } 53 return 0; 54 }View Code