cf Educational Codeforces Round 47 B. Minimum Ternary String

原题:
B. Minimum Ternary String
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard 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

#include <bits/stdc++.h>

using namespace std;


typedef long long ll;
string s;

int main()
{

    ios::sync_with_stdio(false);
    while(cin>>s)
    {
        int two=-1;
        for(int i=0;i<s.size();i++)
        {
            if(s[i]=='2')
            {
                two=i;
                break;
            }
        }

        if(two==-1)
        {
            sort(s.begin(),s.end());
            cout<<s<<endl;
            continue;
        }
        sort(s.begin(),s.begin()+two);
        cout<<string(s.begin(),s.begin()+two);
        string tmp="";
        int one=0;
        for(int i=two;i<s.size();i++)
            if(s[i]=='1')
                one++;
            else
                tmp+=s[i];

        for(int i=0;i<one;i++)
            cout<<'1';
        cout<<tmp<<endl;



    }
    return 0;
}

思路:

首先找到第一个2所在的位置,如果没有2,直接所有的0在前,1在后即可。如果有2,那么找到第一个2的位置,将2之前的所有0都排到最前面,然后将整个序列的1都排到0后面,剩下的部分直接输出即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值