Minimum Ternary String (CodeForces - 1009B)(思维题)

版权声明:莉莉莉 https://blog.csdn.net/qq_41700151/article/details/82949679

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 105 (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可以交换,1和0也可以交换,0和2不能交换,通过一番操作之后,找出字典序最小的一个串;
**分析:**由题意可知,1可以和这两个数换,所以1可以在这个串中随意滑动,但是第一个2后面的0就不可以换到这个2前面来,辣么这个题就是找第一个2前面所有的0全部输出,再输出所有的1,第一个2之后的所有不为1的数全部原样输出,注意000111这个样例。
代码:

#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
using namespace std;
int main()
{
   int a[4];
   ios::sync_with_stdio(false);
   memset(a,0,sizeof(a));
   string s;
   cin>>s;
   int n=s.size();
   int k=n;               //k初始化为n保证000111这组样例
   for(int i=n-1;i>=0;i--)
   {
       if(s[i]=='0')
        a[0]++;
       if(s[i]=='2')
        {
            k=i;              //找第一个2的位置
            a[2]++;
        }
       if(s[i]=='1')
        a[1]++;
   }
   for(int i=0;i<k;i++)
   {
       if(s[i]=='0')
        cout<<"0";
   }
   for(int i=0;i<a[1];i++)
    cout<<"1";
   for(int i=k;i<n;i++)
    if(s[i]!='1')
     cout<<s[i];
   return 0;

}

猜你喜欢

转载自blog.csdn.net/qq_41700151/article/details/82949679