Lexicographically smallest problem POJ (3617)

Given a string of length N S, to construct a string of length N T, first, T is a null string, then any of the following are repeated.

To delete a character from the head of S, T added to the tail

S delete a character from the tail, and the tail added to the T

The goal is to construct the lexicographically smallest possible string T.

 

Greedy can, but note that if the head and tail of the case where the same lexicographic order, comparing the size of two letters deeper, taking lexicographically smaller side, can not take any side, for example, DABABJGJGJBD, if any to take then, into the first end of the tail T is D, then the next T tail is added to B, but if D taking the left, then the next time the tail T is added to a, the latter apparently string composed of lexicographically smaller. Therefore, in the same case letters on both sides, more preferred inner layer letter lexicographically less side

#include <bits\stdc++.h>
using namespace std;

const int MAX_N = 1000;
int N;
char S[MAX_N + 1];

void solve()
{
    int head = 0;
    int tail = N - 1;

    while (head <= tail)
    {
        bool left = false;

        // 如果相等的话,再进行一次循环……直到分出大小
        for (int i = 0; head + i <= tail; i++)
        {
            if (S[head + i] < S[tail - i])
            {
                left = true;
                break;
            }
            else if(S[head + i] > S[tail - i])
            {
                left = false;
                break;
            }
        }

        if (left)
            putchar(S[head++]);
        else
            putchar(S[tail--]);
    }

    putchar('\n');
}

 

Published 58 original articles · won praise 6 · views 7053

Guess you like

Origin blog.csdn.net/weixin_43569916/article/details/103980143