Codeforces ~ 1009B ~ Minimum Ternary String (思维)

题意

给你一个只含有0,1,2的字符串,你可以将"01"变为"10","10"变为"01","12"变为"21","21"变为"12",问通过变换可以得到的字典序最小的串是什么?

 

题解

一开始天真的以为,我把所有的"10"变为"01",和所有的"21"变为"12"即可。

直到发现了201,20001这种数据,发现思路错了。

首先所有'1'一定能被交换到任意位置,'0'和'2'的相对位置不可能发生改变。

所以我们把所有的'1'放到第一个2的前面就行了。

AC代码:

#include <bits/stdc++.h>
using namespace std;
string s, ans;
int main()
{
    cin >> s;
    int one = 0;
    for (int i = 0; i < s.size(); i++)
    {
        if (s[i] == '0') ans += "0";
        if (s[i] == '1') one++;
        if (s[i] == '2') ans += "2";
    }
    bool flag = false;
    for (int i = 0; i < ans.size(); i++)
    {
        if (ans[i] == '2' && !flag) flag = true, cout << string(one, '1');
        cout << ans[i];
    }
    if (!flag) cout << string(one, '1');
    return 0;
}
、
View Code
原文地址:https://www.cnblogs.com/shuaihui520/p/9322127.html