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

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

题意:给定一个字符串,只包含0 1 2 ,你可以交换(0 1 )(1 0)(2 1)(1 2)问你可达到的最小序列是多少
思路:很明显0 2 的相对位置是不能动的,1可以随意去到然任何位置,所以只要找到第一个出现2的位置,然后把所有的1全部放到它前面的就可以了。

代码:

#include<bits/stdc++.h>
#define LL long long
#define Max 100005
const LL mod=1e9+7;
const LL LL_MAX=9223372036854775807;
using namespace std;
char a[Max],ans[Max];
int main()
{
    cin>>a;
    int c=0,len=strlen(a),lenans=0;
    for(int i=0;i<len;i++){
        if(a[i]=='1')
            c++;
        else
            ans[lenans++]=a[i];
    }
    int index=0;
    while(ans[index]=='0' && index<lenans)
        index++;
    if(lenans==0){//只包含1,直接输出
        printf("%s\n",a);
        return 0;
    }
    ans[lenans]=' ';
    for(int i=0;i<=lenans;i++){
        if(i==index)
            for(int j=0;j<c;j++)
                printf("%c",'1');
        printf("%c",ans[i]);
    }
    printf("\n");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Gee_Zer/article/details/89288093