Skip to content

03376: Best Cow Line, Gold

greedy, two pointers , http://cs101.openjudge.cn/practice/03376

FJ is about to take his N (1 ≤ N ≤ 30,000) cows to the annual "Farmer of the Year" competition. In this contest every farmer arranges his cows in a line and herds them past the judges.

The contest organizers adopted a new registration scheme this year: simply register the initial letter of every cow in the order they will appear (e.g., If FJ takes Bessie, Sylvia, and Dora in that order, he just registers BSD). After the registration phase ends, every group is judged in increasing lexicographic order (i.e., alphabetical order) according to the string of the initials of the cows' names.

FJ is very busy this year and has to hurry back to his farm, so he wants to be judged as early as possible. He decides to rearrange his cows, who have already lined up, before registering them.

FJ marks a location for a new line of the competing cows. He then proceeds to marshal the cows from the old line to the new one by repeatedly sending either the first or last cow in the (remainder of the) original line to the end of the new line. When he's finished, FJ takes his cows for registration in this new order.

Given the initial order of his cows, determine the least lexicographic string of initials he can make this way.

输入

* Line 1: A single integer: N

* Lines 2..N+1: Line i+1 contains a single initial ('A'..'Z') of the cow in the ith position in the original line

输出

The least lexicographic string he can make. Every line (except perhaps the last one) contains the initials of 80 cows ('A'..'Z') in the newline.

样例输入

6
A
C
D
B
C
B

样例输出

ABCBCD

提示

INPUT DETAILS:

FJ has 6 cows in this order: ACDBCB

OUTPUT DETAILS:

  Step   Original     New
   #1     ACDBCB
   #2      CDBCB     A
   #3      CDBC      AB
   #4      CDB       ABC
   #5      CD        ABCB
   #6       D        ABCBC
   #7                ABCBCD

来源:DEC07

解题思路:

字典序是指从前到后比较两个字符串大小的方法。首先比较第1个字符,如果不同则第1个字符较小的字符串更小,如 果相同则继续比较第2个字符⋯⋯如此继续,来比较整个字符串的大小。

从字典序的性质上看,无论m末尾有多大,只要前面部分的较小就可以。所以我们可以试一下 如下贪心算法: ■不断取的开头和末尾中较小的一个字符放到m末尾。 这个算法已经接近正确了,只是针对的开头和末尾字符相同的情形还没有定义。在这种情形下, 因为我们希望能够尽早使用更小的字符,所以就要比较下一个字符的大小。下一个字符也有可能 相同,因此就有如下算法: ■按照字典序比较S和将反转后的字符串S' ■如果S较小,就从S的开头取出一个文字,追加到T的末尾。 ■如果S较小,就从S的末尾取出一个文字,追加到T的末尾。 (如果相同则,则继续比较) 根据前面提到的性质,字典序比较类的问题经常能用得上贪心法。

Python超时,C++可以AC。

python
# Time Limit Exceeded
n = int(input())
S = []
for _ in range(n):
    S.append(input())

a = 0
b = len(S) - 1
ans = []
cnt = 0
while a <= b:
    bLeft = False
    for i in range(b-a+1):
        if S[a+i] < S[b-i]:
            bLeft = True
            break
        elif S[a+i] > S[b-i]:
            bLeft = False
            break
    
    cnt += 1
    if bLeft:
        #print(S[a], end='')
        ans.append(S[a])
        a += 1
    else:
        #print(S[b], end='')
        ans.append(S[b])
        b -= 1
    if cnt%80 == 0:
        ans.append('\n')
    
print(''.join(ans))
c++
#include <iostream>
#include <cstdio>
using namespace std;

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

void solve(){
    int a = 0, b = N - 1;

    int cnt = 0;
    while (a <= b) {
        bool left = false;
        for (int i = 0; a + i <= b; i++){
            if (S[a +i] < S[b - i]){
                left = true;
                break;
            }
            else if (S[a +i] > S[b -i]){
                left = false;
                break;
            }
        }

        cnt ++;
        if (left) putchar(S[a++]);
        else putchar(S[b--]);
        if (cnt%80 == 0)
            putchar('\n');
    }
    
}
int main()
{
    cin >> N;
    for (int i = 0; i<N; i++)
        cin >> S[i];
    solve();
    return 0;
}