cf Educational Codeforces Round 47 B. Minimum Ternary String

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tengfei461807914/article/details/82190583

原题:
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后面,剩下的部分直接输出即可。

猜你喜欢

转载自blog.csdn.net/tengfei461807914/article/details/82190583