Educational Codeforces Round 47 (Rated for Div. 2) :B. Minimum Ternary String

题目链接:http://codeforces.com/contest/1009/problem/B

 

解题心得:

  • 题意就是给你一个只包含012三个字符的字符串,位置并且逻辑相邻的字符可以相互交换位置,就是相邻的01交换,12交换,不可以02交换。最后需要输出字典序最小的字符串。
  • 其实想想就很容易明白在字符串中1是可以随便移动的,所以可以把字符串中的1全删除,就只剩下02两种字符,这两种字符的相对位置不可以改变。然后把所有的1插在第一个02之间。
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5+100;

char s[maxn], ans[maxn];
int len, cnt_1;
void init(){
    scanf("%s",s);
    len = strlen(s);
    for(int i=0;i<len;i++)
        if(s[i] == '1')
            cnt_1++;
}

void solve(){
    if(cnt_1 == len) {//只有1的情况
        printf("%s",s);
        return ;
    }
    int tot = 0,i,j;
    for(i=0;i<len;i++) {//找到第一个02中间
        if(s[i] == '0') {
            ans[tot++] = s[i];
        } else if(s[i] == '1'){
            continue;
        } else {
            while(cnt_1--) {
                ans[tot++] = '1';
            }
            break;
        }
    }
    for(j=i;j<len;j++) {
        if(s[j] == '1')
            continue;
        else
            ans[tot++] = s[j];
    }
    int len_ans = strlen(ans);
    if(len_ans < len){//只有01的情况补1
        for(int j=len_ans;j<len;j++)
            ans[tot++] = '1';
    }
    ans[tot] = '\0';
    printf("%s", ans);
}

int main() {
    init();
    solve();
}

 

posted @ 2018-07-24 10:20  GoldenFingers  阅读(152)  评论(0编辑  收藏  举报