B. Minimum Ternary String
time limit per test:1 second
memory limit per test:256 megabytes
input:standard input
output:standard output
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 10^5 (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
题目:给定一个字符串(只有‘1’,‘2’,‘0’组成),其中'1'和‘0’可以交换,‘2’和‘1’可以交换,要求找交换操作后最小的字符串;
思路:我们发现'1'可以跟‘0’和‘2’交换,即‘1’可以到达任何地方,所以我们将‘1’删除,将所有的‘1’放到第一个‘2’前面,如果没有‘2’就放在最后好啦!!!
代码:
#include<bits/stdc++.h>
#define ll long long
using namespace std;
string s, ans;
int main()
{
while(cin >> s)
{
ans.erase();
int len = s.length(), cnt = 0, pos = 0;
for(auto c : s)
if(c == '1') cnt++;
else ans += c;
while(pos < len&&ans[pos] == '0') pos++;
ans.insert(pos, cnt, '1');
cout << ans << endl;
}
return 0;
}
这个思路,我没有在场上想到,好伤心!!!