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 a is lexicographically less than string b (if strings a and b have the same length) if there exists some position i(1≤i≤|a|, where |s| is the length of the string s) such that for every j<i holds aj=bj, and ai<bi.
Input
The first line of the input contains the string s consisting only of characters ‘0’, ‘1’ and ‘2’, its length is between 1 and (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).
Input
100210
Output
001120
题意:
输入:给出一个有‘0’、‘1’、‘2’组成的字符串
条件:可以交换任意相邻的‘0’和‘1’,或者‘1’和‘2’,但是不能交换‘0’和‘2’,目的:通过任意的交换,得到尽可能小的字符串。
分析:
- 对于‘1’:
我们知道‘1’可以跟‘0’交换,也可以跟‘2’交换,也即是说,‘1’在字符串中 的位置是自由的,为了获得最小的字符串,要所有的‘1’移动到‘0’的后面
统计字符‘1’出现的个数
- 对于‘0’:
因为不能与‘2’交换,我们分两种情况考虑:
1、在第一个‘2’前面的(为了尽可能小,可以把‘0’全部放在最前面)
2、在第一个‘2’后面的(不可能通过交换操作,放到‘2’前面)
确定第一个‘2’的位置,以及第一个‘2’前面‘0’的个数
- 对于’2’:
在重新排列之后,‘2’之后应该只剩下出现在第一个’2‘后面的‘0’和剩下的‘2’,只需要重新遍历第一个‘2’后面的字符串,跳过‘1’然后依序输出
重新遍历第一个‘2’后面的字符串,跳过‘1’然后依序输出
代码
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s;
cin>>s;//输入字符串
int len=s.size();//字符串的长度
int pos;//第一个2的位置
int numzero=0;
int numone=0;//记录整个字符串中间1的个数,以及第一个2前的0的个数
int i;
int flag=0;//标示字符串中是否存在2
//找出第一个2的位置,并确定numzero,numone;
for(i=0;i<len;i++)
{
if(s[i]=='2'&&flag==0){
pos=i;
flag=1;
}
if(s[i]=='0'&&flag==0){
numzero++;
}
if(s[i]=='1'){
numone++;
}
}
for(i=0;i<numzero;i++){
cout<<"0";
}
for(i=0;i<numone;i++){
cout<<"1";
}//输出0,1
if(flag==1){
for(i=pos;i<len;i++)
{
if(s[i]=='1') continue;
else cout<<s[i];
}
}//从第一个2的位置开始遍历输出字符串,跳过1;
return 0;
}