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

本文探讨了一种特定的字符串操作问题,目标是最小化由字符0、1、2组成的三元字符串。通过允许交换相邻的0与1以及1与2,文章提供了一个高效的算法来达到最小的字典序。关键在于保持0与2的相对位置不变,同时将所有1移至首个2之前。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值